Problem with GetComponent returning a null object yet working a bit later

    private MonsterPathJumps monsterPathJumps;

    // Use this for initialization
    public new void Start () {
        base.Start();

        monsterPathJumps = GetComponent<MonsterPathJumps>();

        if (monsterPathJumps == null) Debug.Log("MonsterPathJump NULL");

        monsterPathJumps.SetCollider(bodyCollider);
        if (monsterPathJumps == null) Debug.Log("MonsterPathJump NULL");
       
    }

When this code runs, I get the first log entry MonsterPathJump NULL

Then I get

NullReferenceException: Object reference not set to an instance of an object
Spring.Start () (at Assets/Scripts/Monsters/Spring.cs:19)

which points to this line:

monsterPathJumps.SetCollider(bodyCollider);

Yet the code inside SetCollider is executed, and I do not get the second MonsterPathJump NULL log.

the bodyCollider is not null, it is set in the base.Start() call and I’ve tested it.

Every component is in the same GameObject

Do I need to have wait time after GetComponent to be sure it’s loaded? Should I put all my GetComponent calls in Awake()? Is there something else I am missing?

Thanks!

Hm. Well, you wouldn’t get the second debug log if the line gives you a null ref because the method would be exited. There must be other code running the SetCollider, because if it’s a null value there for monsterPath, it can’t possibly be running it… :slight_smile:

oh right you are correct. I shouldn’t debug this late, makes me miss the obvious. Can’t figure out what else is calling that function. I just created it and made that one call. I’ll keep looking. Thanks for steering me in the right direction!

np, hope you figure it out :slight_smile:

Also, in regards to your question about GetComponent, I think it’s usually best to call it in Awake (mostly, because you can safely, and also in case it’s needed by other scripts in their Start methods). However, if it’s not needed elsewhere, Awake or Start … doesn’t matter. :slight_smile: