Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

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

Discussion in 'Scripting' started by smurftra, Feb 3, 2018.

  1. smurftra

    smurftra

    Joined:
    Jan 16, 2018
    Posts:
    9
    Code (csharp):
    1.  
    2.     private MonsterPathJumps monsterPathJumps;
    3.  
    4.     // Use this for initialization
    5.     public new void Start () {
    6.         base.Start();
    7.  
    8.         monsterPathJumps = GetComponent<MonsterPathJumps>();
    9.  
    10.         if (monsterPathJumps == null) Debug.Log("MonsterPathJump NULL");
    11.  
    12.         monsterPathJumps.SetCollider(bodyCollider);
    13.         if (monsterPathJumps == null) Debug.Log("MonsterPathJump NULL");
    14.        
    15.     }
    16.  
    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!
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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... :)
     
  3. smurftra

    smurftra

    Joined:
    Jan 16, 2018
    Posts:
    9
    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!
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    np, hope you figure it out :)

    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. :)