c# - 如何在 Unity 中为游戏添加重启功能?

标签 c# unity3d

我已经关注并完成了一个 Unity tutorial然而,一旦教程说完了,就没有提到重新启动游戏的功能。

除了关闭应用程序并重新打开之外,我将如何添加这样的内容?

最佳答案

在 Unity 中有很多重启游戏的方法:

1.将位置、旋转、得分等所有有用的变量重置为默认位置。当您使用此方法而不是#2时,您将减少游戏加载所需的时间。

创建一个 UI 按钮,然后将其拖到编辑器中的 resetButton 槽中。

//Drag button from the Editor to this
public Button resetButton;

Vector3 defaultBallPos;
Quaternion defaultBallRot;
Vector3 defaultBallScale;
int score = 0;


void Start()
{
    //Get the starting/default values
    defaultBallPos = transform.position;
    defaultBallRot = transform.rotation;
    defaultBallScale = transform.localScale;
}

void OnEnable()
{
    //Register Button Event
    resetButton.onClick.AddListener(() => buttonCallBack());
}

private void buttonCallBack()
{
    UnityEngine.Debug.Log("Clicked: " + resetButton.name);
    resetGameData();
}

void resetGameData()
{
    //Reset the position of the ball and set everything to the starting postion
    transform.position = defaultBallPos;
    transform.rotation = defaultBallRot;
    transform.localScale = defaultBallScale;

    //Reset other values below
}

void OnDisable()
{
    //Un-Register Button Event
    resetButton.onClick.RemoveAllListeners();
}

2.调用SceneManager.LoadScene("sceneName");再次加载场景。您可以在 Button.onClick.AddListener 时调用此函数被称为..

创建一个 UI 按钮,然后将其拖到编辑器中的 resetButton 槽中。

//Drag button from the Editor to this
public Button resetButton;

void OnEnable()
{
    //Register Button Event
    resetButton.onClick.AddListener(() => buttonCallBack());
}

private void buttonCallBack()
{
    UnityEngine.Debug.Log("Clicked: " + resetButton.name);

    //Get current scene name
    string scene = SceneManager.GetActiveScene().name;
    //Load it
    SceneManager.LoadScene(scene, LoadSceneMode.Single);
}

void OnDisable()
{
    //Un-Register Button Event
    resetButton.onClick.RemoveAllListeners();
}

使用哪种方法取决于场景中有多少对象以及加载场景需要多长时间。如果场景有一个带有烘焙光照贴图和 HQ 纹理的巨大世界,那么选择 #1。

关于c# - 如何在 Unity 中为游戏添加重启功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44288452/

相关文章:

c# - 在 void 函数中为 for 循环增加速度?

c# - 通过 GET 发送到 MVC Controller 的 GUID JSON 列表在到达时为空,POST 有效

c# - 使用 Contains 在 SQLite 中搜索非英文文本会返回比预期更多的结果

c# - 如何将我的代码从 UnityScript 切换到 C# (csharp)?

ios - 统一的阿拉伯语输入字段

c++ - WP8 : how to get back an IntPtr in c++

c# - 如何将 100 行插入到只有标识列的单个表中?

c# - List<T>.ForEach() 方法消失了吗?

c# - 如何在代码隐藏中从 Application.Resources 访问命名资源?

c# - Unity Player 正在向自己射击