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\$

1 Answer 1

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
    Commented Apr 23, 2020 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
    Commented Apr 24, 2020 at 5:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .