Unity和C#:在方法内的同一类中访问公共变量

时间:2018-11-13 18:53:27

标签: c# unity3d

这是完整的错误(在这种新情况下,它是NullReferenceException):

NullReferenceException: Object reference not set to an instance of an object
FightScript.startFight_Click () (at Assets/Scripts/FightScript.cs:105)
UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:166)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:58)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update()

代码如下:

public void startFight_Click()                // line 100
{   
    ...
    Debug.Log(strengthHeroValue.ToString());  // line 105 here
    ...
}

strengthHeroValue在类级别被声明为公共,如下所示:

public Text strengthHeroValue;

在用户界面中,在FightScript(脚本)部分中,将strengthHeroValue分配给了ValueText。

我有一个名为startButton的按钮,在On Click()部分中,我选择了FightController,然后选择了FightScript.startFight_Click()事件。

当我双击该错误时,它将带我进入第100行的startFight_Click()方法。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我无法证明这一点,但这是我认为可以考虑您评论中的提示的唯一合理的解释。所以去了:

未抛出NullReferenceException,因为您试图访问name内部的starFight_Click。在您的onClick事件尝试调用starFight_Click时引发。 onClick事件没有对脚本实例的有效引用,但尝试在startFight_Click上调用null,这是导致NullReferenceException的原因。检查您的事件处理程序。