Unity DontDestroyOnload()

时间:2016-02-01 20:00:44

标签: c# unity3d

我的播放器在加载新场景时处于上一级别的位置。有没有办法为此制作一个生成点?

我使用DoontDestoryOnLoad函数让玩家进入下一个场景,但是当玩家加载时,玩家将以与他相同的x位置产生。

public class DontDestroyPlz:MonoBehaviour {

// 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:MonoBehaviour,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)
{

}

}

1 个答案:

答案 0 :(得分:2)

使用方法OnLevelWasLoaded。每次加载新场景时都会调用它。例如,您可以为每个场景预定玩家位置:

Vector3 positionLevel1;
Vector3 positionLevel2;

void OnLevelWasLoaded(int level) 
{
    if (level == 1)
       transform.position = positionLevel1;
    else if (level == 2)
       transform.position = positionLevel2;
}