0
\$\begingroup\$

I have a component gameState Attached to one gameobject called GameState:

public class gameState : MonoBehaviour
    {
        public Context stateMachine;
        private void Awake()
        {
            PlayerGameobject p = GameObject.Find("Player").GetComponent<PlayerGameobject>();
            stateMachine = new Context(new Playing(), p); 
        }

On another gameObject I have this component:

public class PlayerGameobject : MonoBehaviour
{
    void Start()
    {

        gameState = GameObject.Find("GameState").GetComponent<gameState>();
    }

}

When I try to use gameState within PlayerGameobject's Update method I find that stateMachine is null.

 if (gameState.stateMachine.CurrentState == "Playing"){}
      //       ^^^^ null   

why is statemachine null? I initialized it in awake which should run before start. gameState is not null and other public variables assigned in Editor are not null.

\$\endgroup\$
0
\$\begingroup\$

The provided code won't work properly since you name your class gameState and access gameState.stateMachine while stateMachine is not static. Make sure you access the stateMachine of the GameState instance.

Another guess: it might be possible that the new Context(...) in your gameState Awake causes an exception which leads to stateMachine being null. You would directly spot that in the console though.

\$\endgroup\$
2
  • \$\begingroup\$ The error was inside new Context, Hidden among the spam of errors the update method was giving. Turns out that unity will abort the Awake method if it come across a nullReference error. \$\endgroup\$ – Jacob Edie Apr 23 '20 at 20:45
  • \$\begingroup\$ That aborting is really a thrown Exception. Exceptions are thrown upwards unless you catch them with a try-catch block. \$\endgroup\$ – schneebuzz Apr 24 '20 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.