0

I've a panel in my scene (ErrorMessage), I've been disabled it in the editor and writed this in my C# script:

            if(getUsernameResponse == "Login OK") {
                Application.LoadLevel("LobbyUI");
            } else {
                GameObject ErrorMessage = GameObject.FindGameObjectWithTag("ErrorMessage");
                ErrorMessage.SetActive(true);
            }

The script should enable (show) my ErrorMessage if getUsernameResponse have a different response of "Login OK".. but when I start the liveDemo I see this error:

NullReferenceException: Object reference not set to an instance of an object) in row:41 (ErrorMessage.SetActive(true);)

I've tried to enable the ErrorMessage from the editor and disable with

if(getUsernameResponse == "Login OK") {
                Application.LoadLevel("LobbyUI");
            } else {
                GameObject ErrorMessage = GameObject.FindGameObjectWithTag("ErrorMessage");
                ErrorMessage.SetActive(false);
            }

in my source and it works fine, how can I disable ErrorMessage (UI.Panel) from my script?

Thanks for support.

4

2 回答 2

3

它只是意味着:

GameObject ErrorMessage = GameObject.FindGameObjectWithTag("ErrorMessage");

没有找到游戏对象。

可能是因为您实际上没有在 GameObject 上放置标签,或者标签拼写错误。并且一定要记住层不是标签!

真的,我不知道你的整个设置,但我怀疑你在做什么,你真的不应该做。为 errorMessage 对话创建标签?我在 Unity 中编写了很多 UI。我从来没有在 UI 中标记过任何东西。标记应该用于场景中您需要轻松抓取的对象类型的非常通用的分组。TeamA,TeamB,AI,通电。它不应该只用于抓取一个具有非常特殊性质的对象。

我会使用 GameObject.Find 并按实际 GameObject 的名称搜索它。

或者我会按照 Miron Alex 所说的在检查器中创建一个插槽,然后将 GameObject 拖入其中。理想情况下应该是一个序列化的私有变量。

[SerializeField]
private GameObject errorMessage;
于 2015-03-02T08:35:56.873 回答
1

当对象为“null”时抛出 NullReferenceException,因为它不存在。在您的代码中,该方法

GameObject.FindGameObjectWithTag("ErrorMessage"); 

没有找到任何带有“ErrorMessage”标签的对象,这意味着它返回“null”并将“null”分配给 ErrorMessage GameObject。当您尝试在“null”对象上调用方法时,它会抛出“NullReferenceException”,因为“null”值对“SetActive(bool value)”方法一无所知(就像 GameObject 一样)。

确保场景中有一个标记为“errorMessage”的对象。为了让这更容易,在你的代码中创建一个公共游戏对象,将它命名为 ErrorMessage 并在检查器中分配它。

public GameObject errorMessage;

if(getUsernameResponse == "Login OK") 
{
   Application.LoadLevel("LobbyUI");
} 
else 
{
   errorMessage.SetActive(false);
}

应该做的伎俩。

于 2015-03-02T07:28:52.960 回答