尝试从inputfield获取文本时出现NullReferenceException

时间:2015-07-23 08:07:24

标签: text unity3d nullreferenceexception input-field

我是团结的新手,想要从输入文本字段中获取值。我发现了这个问题 Get text from Input field in Unity3D with C#,但是当我执行它时,总会出现相同的错误:NullReferenceExcpetion:对象引用未设置为对象的实例。 这似乎是一个愚蠢的错误,我尝试了一切但似乎无法解决它。 我的代码:

void Start () {
    var input = gameObject.GetComponent<InputField>();
    input.onEndEdit.AddListener(SubmitName);

}

private void SubmitName(string arg0)
{
    Debug.Log(arg0);
}

我尝试了InputField input;在开始功能和删除var之前,但仍然没有运气。 如果有人能帮我解决这个问题,我将不胜感激。 此刻我的脚本所附的图片。 enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您的代码几乎是正确的,如果您have a look at the documentation,则必须在调用方法名称之前使用function调用方法。它看起来像你在混合c#JS,这里是`js函数:

public class Example {
    public var mainInputField;
    public function Start() {
        // Adds a listener to the main input field 
        // and invokes a method when the value changes.
        mainInputField.onValueChange.AddListener(function() {
            ValueChangeCheck();
        });
    }
    // Invoked when the value of the text field changes.
    public function ValueChangeCheck() {
        Debug.Log("Value Changed");
    }
}

c#解决方案:

public class MenuController : MonoBehaviour {

    [SerializeField]
    InputField inputText;

    // Use this for initialization
    void Start () {
        inputText.onValueChange.AddListener(delegate {
            DebugInput();
        });
    }

    private void DebugInput(){
        Debug.Log ("Input: " + inputText);
    }
}

我的Hierarchie看起来像这样:

我创建了一个Canvas并在其中插入了InputField。包含内部代码的脚本附加到Canvas中的InputField[SerializeField]连接到Canvas脚本中的InputField

我建议您将[SerializeField]作为类变量,以便以后更轻松地访问它。此外,您应该为InputField创建<input type="button" id="btn" value="Click Me"></input> <div id="someContent" hidden>Some Content</div> <div id="videoContent">Video Content</div> ,以便将其拖到脚本中。这也可以避免一些错误。