2017-05-31 2699 views
0

我跟随并完成了一个Unity tutorial然而,一旦教程被说完并完成,就没有提到重新启动游戏的功能。如何将重新启动功能添加到Unity中的游戏?

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

+2

的可能的复制[Unity3d重启当前场景](https://stackoverflow.com/questions/41644156/unity3d-restart-current-scene) – Hellium

回答

4

有根本的方法来重新启动游戏在Unity:

.reset段每一个有用的变量,如位置,旋转,比分为它们的默认位置。当你使用这种方法,而不是#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(); 
} 

.CALL 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。

+0

个人而言,我更喜欢使用的场景管理 –

+4

@SpencerPollock其实,这不是在这种情况下的偏好问题。如果你有装载烘焙地图和HQ纹理的巨大场景,你应该重置变量以节省加载玩家时间的时间。如果这是一个小场景,那就用#2进行。 – Programmer

+1

感谢您的回复。 我应该添加我是一个100%的新手,那个教程是我第一次尝试。 因此,我有点难以理解如何实施您所概述的步骤。 能否详细说明一下?我确实尝试了解文档以作进一步解释。 – CDoc

-1

例如,您可以重新加载主场景以重新启动游戏。

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);