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

NullExceptionError Help

Discussion in 'Scripting' started by jasfiqrahman15, Jan 15, 2020.

  1. jasfiqrahman15

    jasfiqrahman15

    Joined:
    Jan 15, 2020
    Posts:
    3
    Code (CSharp):
    1.  
    2. _player = GameObject.FindWithTag("Player").GetComponent<Player>();
    3. if (_player == null)
    4.             Debug.LogWarning("Enemy Player is null.");
    5. _playerOne = GameObject.FindWithTag("Player One").GetComponent<Player>();
    6. if (_playerOne == null)
    7.             Debug.LogWarning("Enemy Player One is null.");
    8. _playerTwo = GameObject.FindWithTag("Player Two").GetComponent<Player>();
    9. if (_playerTwo == null)
    10.             Debug.LogWarning("Enemy Player Two is null.");
    11.  
    This is my code. I have two scenes in my game, one where there is a single player with the tag player, and the other where I have two players with the respective other tags. thing is, I've discovered after a lo of debugging that the code runs till these lines, then a NullExceptionError occurs and the code begins from the, well beginning. How can I make them iterate over, for I was under the assumption that even if a null value came, the value will just be set as null and the game will continue to the next line. What exactly is the problem here?
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,256
    Code (CSharp):
    1. _player = GameObject.FindWithTag("Player").GetComponent<Player>();
    That line right there. If GameObject.FindWithTag() doesn't find anything it will be null. Trying to call GetComponent() on a null object will give you a null reference exception.

    Code (CSharp):
    1. _player = GameObject.FindWithTag("Player");
    2.  
    3. if (!_player)//Does the same as _player == null
    4.      Debug.LogWarning("Enemy Player is null.");
     
  3. jasfiqrahman15

    jasfiqrahman15

    Joined:
    Jan 15, 2020
    Posts:
    3
    My mind totally skipped that! Thanks a lot, I appreciate it.