简体   繁体   中英

Unknown NullReferenceException in C# with class references

I read this explanation of NullReferenceException in C# but couldn't find an answer.

I'm working in Unity5 (2D) and trying to make a button that, when clicked, activates a method in the script of another object.

In the classes, I added comments like //(line #) so you can reference from the NRE easier.

public class runePadController : MonoBehaviour {
public void shoot() {
    var fccClass = new friendlyCastleController();
    fccClass.shoot(); //(Line 23)
}
}

The button activates the shoot() method in the above class.

public class friendlyCastleController : MonoBehaviour {
public void shoot() {
    useElement (true, "fireBall"); //(Line 36)
}

public void useElement (bool atk, string type)
{
    switch (type)
    {
        case "fireBall":
            if (atk)
            {
                //Object clone;
                Vector3 nPosition = new Vector3();
                float nX = transform.position.x + Random.Range(-5F, 5F); //(Line 48)
                float nY = transform.position.y + 3F;
                nPosition.Set(nX, nY, 0);

                Quaternion nAngle = new Quaternion();
                nAngle.Set(Random.Range(-0.15F, 0.15F), 1, 0, 0);
                //Debug.Log(nPosition + " :: " + nAngle);

                //clone = (Instantiate(fireBallPF, nPosition, nAngle)) as GameObject;
                Instantiate(fireBallPF, nPosition, nAngle);
            }
            else
            {

            }

            break;
        default:
           Debug.Log ("Error: Default Switch Called in FriendlyCastleController");
            break;
    }
}

...and this is part of the class which deals with the called method.

However, Unity throws this at me:

NullReferenceException
friendlyCastleController.useElement (Boolean atk, System.String type) (at Assets/Scripts/friendlyCastleController.cs:48)
friendlyCastleController.shoot () (at Assets/Scripts/friendlyCastleController.cs:36)
runePadController.shoot () (at Assets/Scripts/runePadController.cs:23)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:144)
UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:621)
UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:756)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
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:269)
UnityEngine.EventSystems.EventSystem:Update()

To anyone who understands this better, can you point me in the right direction?

Thanks! :)

Try assigning the friendlyCastleController class to the gameObject from where you are taking transform.position values, and in runePadController instead for creating a new friendlyCastleController use,

var fccClass = gameObjectName.getComponent<friendlyCastleController>();

OP, everything you are doing is completely wrong :

This statement

 var fccClass = new FriendlyCastleController();

is completely meaningless and does not exist in Unity. Unity is not an OO system, it is an ECS system. There is no inheritance nor any OO concepts whatsoever. This line

 public class FriendlyCastleController:MonoBehaviour

means that FriendlyCastleController is a MonoBehavior . What does that mean? It means it is a component you attach to an actual specific GameObject .

It can not exist on its own , it can only exist as an attachment to a game object .

  1. in the editor make a new game object (perhaps a small cube for example) called AAA

  2. actually attach a FriendlyCastleController script to that object

  3. make a new script called Test.cs, also a monobehavior, and attach Test.cs to some other object called BBB

  4. In Test.cs, do this

      public FriendlyCastleController friendlyCastle; 
  5. Now LOOK in the Editor at BBB. Notice you can actually drag to the slot "friendlyCastle". Do that - in fact drag from AAA .

Now you understand how Unity works.

in RunePadController you must have a

      public FriendlyCastleController friendlyCastle;

and you drag your "AAA" object (in the example here) to that. Later, you can learn how to "Find" the "AAA" object on the fly inside RunePadController.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM