在团结中抛出例外

时间:2015-06-02 21:29:18

标签: c# unity3d

我正在开发一个非常简单的脚本,它使用带有InputField和按钮的画布。当玩家按下按钮时,脚本会检查输入字段的文本。我遇到的问题是,如果没有输入任何内容,Unity将以UnassignedReferenceException退出。

我尝试捕获该异常,但我必须做一些可怕的错误:

public class Quiz : MonoBehaviour {

    public GameObject quizPanel;
    public GameObject input;

    public void checkAnswer(){

        Text answer = (input.GetComponent<Text>()) as Text;

        try {
            if (answer.text == "George Washington") {
                Debug.Log("True");
            }
        }catch (UnassignedReferenceException)
        {
            Debug.Log ("Wrong answer");
        }
    }
}

2 个答案:

答案 0 :(得分:3)

1)我将所有代码放入try-catch

2)确保记录您的例外情况。

public class Quiz : MonoBehaviour {

    public GameObject quizPanel;
    public GameObject input;

    public void checkAnswer(){
        try {
        Text answer = (input.GetComponent<Text>()) as Text;


            if (answer.text == "George Washington") {
                Debug.Log("True");
            }
        }catch (UnassignedReferenceException ex)
        {
            Debug.Log ("Wrong answer");
            Log.Item(ex); 

        }
    }
}

答案 1 :(得分:2)

我有充分的理由相信您的input变量在某种程度上无效。所以我建议你让try/catch封装你的所有代码:

public void checkAnswer(){
    try {
        Text answer = (input.GetComponent<Text>()) as Text;

        if (answer.text == "George Washington") {
            Debug.Log("True");
        }
    }catch (UnassignedReferenceException)
    {
        Debug.Log ("Wrong answer");
    }
}