如果If语句失败,我可以调用函数吗?

时间:2015-01-19 12:12:12

标签: c# function if-statement unity3d

void Update()
{
    bool playerInView = false;

    foreach (RaycastHit hit in eyes.hits)
    {
        if (hit.transform && hit.transform.tag == "Player")
        {
            playerInView = true;
        }
    }

    if (playerInView)
    {
        print ("Detected");
    }
    else
    {
        void OnGUI () {
            GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
        }
    }
}

}

当我在Unity中运行时,它表示void不能在此上下文中使用 但当我删除功能,只是调用打印然后它工作

4 个答案:

答案 0 :(得分:2)

部分

else
{
    void OnGUI () {
        GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
    }
}

是无效的C#语法;函数不能以这种方式在本地定义。也许你的意思是

else
{
    GUI.Box(new Rect (10, 10, 100, 90), "Loader Menu");
}

答案 1 :(得分:1)

尝试:

if (playerInView)
{
    print ("Detected");
}
else
{
    GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
}

答案 2 :(得分:1)

以这种方式做到:

bool playerInView = false;

void Update()
{
    playerInView = false;
    foreach (RaycastHit hit in eyes.hits)
    {
        if (hit.transform && hit.transform.tag == "Player")
        {
            playerInView = true;
        }
    }

    if (playerInView)
    {
        print ("Detected");
    }
}




void OnGUI()
{
    if (!playerInView)
    {
        GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
    }
    ...
}

答案 3 :(得分:0)

首先,尝试在可理解的上下文中写下您的问题。 无论如何,你应该写它,

void Update()
    {
        bool playerInView = false;

        foreach (RaycastHit hit in eyes.hits)
        {
            if (hit.transform && hit.transform.tag == "Player")
            {
                playerInView = true;
            }
        }

        if (playerInView)
        {
            print("Detected");
        }
        else
        {
            OnGUI();
        }
    }
    void OnGUI()
    {
        GUI.Box(new Rect(10, 10, 100, 90), "Loader Menu");
    }