Unity DontDestroyOnload()
本文关键字:DontDestroyOnload Unity | 更新日期: 2023-09-27 18:32:44
我的玩家在加载新场景时在前一个关卡的位置生成。有什么方法可以为此生成一个生成点吗?
我使用了DoontDestoryOnLoad函数将玩家保持在下一个场景中,但是当玩家加载时,玩家将在与他相同的x位置生成。
public class DontDestroyPlz : MonoBehavior {
// Use this for initialization
void Awake()
{
DontDestroyOnLoad(this);
if (FindObjectsOfType(GetType()).Length > 1)
{
Destroy(gameObject);
}
}
// Update is called once per frame
void Update () {
}
}
public class MainMenu : MonoBehavior, IPointerEnterHandler, IPointerExitHandler{
void OnGUI()
{
if (GUI.Button(new Rect(Screen.width / 1.5f, Screen.height / 8, Screen.width / 8, Screen.height / 20), "Bunker"))
{
Application.LoadLevel("Bunker");
}
if (GUI.Button(new Rect(Screen.width / 3.5f, Screen.height / 2.65f, Screen.width / 8, Screen.height / 20), "Forest"))
{
Application.LoadLevel("Forest");
}
GUI.contentColor = Color.white;
GUI.backgroundColor = Color.magenta;
if (GUI.Button(new Rect(Screen.width / 1.5f, Screen.height / 1.5f, Screen.width / 8, Screen.height / 20), "Coming Soon!"))
{
Application.LoadLevel("Desert");
}
GUI.contentColor = Color.white;
GUI.backgroundColor = Color.magenta;
if (GUI.Button(new Rect(Screen.width / 3.0f, Screen.height / 1.5f, Screen.width / 8, Screen.height / 20), "Out of Service"))
{
//Application.LoadLevel("Swamp");
}
}
public void OnPointerEnter (PointerEventData data)
{
Debug.Log ("HERE BRUH!");
}
public void OnPointerExit (PointerEventData data)
{
}
}
使用方法 OnLevelWasLoaded。每次加载新场景时都会调用它。例如,您可以为每个场景预先定义玩家位置:
Vector3 positionLevel1;
Vector3 positionLevel2;
void OnLevelWasLoaded(int level)
{
if (level == 1)
transform.position = positionLevel1;
else if (level == 2)
transform.position = positionLevel2;
}