Search Unity

Trying to add a game object in a list. But gets a NullReferenceException

Discussion in 'Editor & General Support' started by Simoky99, Apr 8, 2020.

  1. Simoky99

    Simoky99

    Joined:
    Apr 8, 2020
    Posts:
    4
    Im instantiating a GameObject then trying to add it into a list in another script. The instatiation happens just fine, but when I try to add the obj into a List, I get the error:
    NullReferenceException: Object reference not set to an instance of an object

    Code (CSharp):
    1.  
    2. public class SpawnUnit : MonoBehaviour
    3. {
    4.     PlayerScript playerScript;
    5.     void Start()
    6.     {
    7.         //playerScript = this.gameObject.GetComponent<PlayerScript>(); //ok
    8.         //playerScript = GameObject.Find("script_holder").GetComponent<PlayerScript>(); //ok
    9.           playerScript = GetComponent<PlayerScript>(); //ok
    10.     }
    11.     public void CreatePlayerUnit(Vector3 location, HeadType head, BodyType body)
    12.     {
    13.         GameObject obj = (GameObject)Instantiate(Resources.Load("prefabs/PlayerCharacter"), location, Quaternion.identity); //ok
    14.         obj.GetComponentInChildren<CharacterStatus>().Created(head, body); //ok
    15.         //playerScript.unitList.Add(obj.transform.Find("AI/'character'").gameObject); //doesn't work
    16.         playerScript.unitList.Add(new GameObject("empty gameobj")); //doesn't work (ERROR HERE)
    17.     }
    18. }
    19.  
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Add debugging. You need to figure out what is null. On line 9, GetComponent is designed to return null if the component is not found, but you're not checking if that occurs. On lines 15 and 16 playerScript.unityList could be null.

    Why aren't you just adding "obj" to the list though? I don't understand your transform.Find and new GameObject lines when the first sentence of your post says you are adding the instantiated GameObject to the list. The instantiated GameObject is obj.
    Code (csharp):
    1. playerScript.unitList.Add(obj);
     
    Simoky99 likes this.
  3. Simoky99

    Simoky99

    Joined:
    Apr 8, 2020
    Posts:
    4
    yes, you are right, for some reason the list was null, now I managed to fix it, thanks!
    and btw I was trying to add the child of the instatiated object
     
    Joe-Censored likes this.
  4. Simoky99

    Simoky99

    Joined:
    Apr 8, 2020
    Posts:
    4
    how do I mark the post as solved?
     
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    If you want you can edit the title. There's no built in forum feature for marking solved though. Glad you got this issue resolved.
     
    Simoky99 likes this.