已分配变量,但该值为null

时间:2016-04-03 18:26:12

标签: c# function debugging variables unity3d

Picture of Error从菜单场景到游戏场景之后。

Picture of Script

我试图在从菜单转换到游戏场景时加载播放器的位置,但是我收到一个错误,说我的变量,播放器为空。我已经在开始和更新函数中打印了我的变量,播放器的值,并且他们都说该播放器有值,但是当我尝试从我的loadPosition函数中从Game场景中访问它时,它给出了一个错误说该播放器一片空白。经过几个小时的思考,我觉得变量播放器为空的原因是因为我从菜单场景而不是游戏场景调用了World()。有没有办法在我之前从不同的场景调用启动函数过渡到游戏场景。这个错误让我疯了!为了便于阅读,我删除了代码中不相关的部分。顺便说一下,Demo是我的游戏场景。提前谢谢!

GameObject player;


    void Update(){

    if (Application.loadedLevelName == "Demo") {
    savePosition ();
    print(player);
    }
}

void Start () {
    if (Application.loadedLevelName == "Demo"){
        player = GameObject.FindWithTag ("Player");
        print (player);
    }

}

public void loadPosition(){

    float playerX = PlayerPrefs.GetFloat ("PlayerX");
    float playerY = PlayerPrefs.GetFloat ("PlayerY");
    float playerZ = PlayerPrefs.GetFloat ("PlayerZ");
    player.transform.position = new Vector3 (playerX, playerY, playerZ);

}


public void savePosition(){


    PlayerPrefs.SetFloat ("PlayerX", player.transform.position.x);
    PlayerPrefs.SetFloat ("PlayerY", player.transform.position.y);
    PlayerPrefs.SetFloat ("PlayerZ", player.transform.position.z);
    float playerX = PlayerPrefs.GetFloat ("PlayerX");
    float playerY = PlayerPrefs.GetFloat ("PlayerY");
    float playerZ = PlayerPrefs.GetFloat ("PlayerZ");
    print (new Vector3 (playerX, playerY, playerZ));
}

1 个答案:

答案 0 :(得分:0)

由于

playernull

player = GameObject.FindWithTag ("Player");

可能会失败。确保GameObject的标签是“播放器”。如果标签不是“播放器”,则FindWithTag将失败。如果发生这种情况,请在编辑器中将该GameObject重命名为“Player”。

然后试试这个:

player = GameObject.Find("Player");

这应解决无效问题。

编辑:

loadPosition()功能移除toWorld(),并将其GameObject.Find("Ethan")放在OnLevelWasLoaded()功能之后print(player)之前