Search code examples
c#listunityscript

List.Count Raises Null Reference Exception


I'm creating a 2D spaceship game in Unity. I have an object titled "Player" with this script attached to it. In the script, I have this class representing the player's ship:

public class Ship : MonoBehaviour 
{
    public List<Weapon> weaponsList;

    void Start()
    {
        weaponsList = new List<Weapon>();
        weaponsList.Add(new Weapon());
        weaponsList.Add(new Weapon());
    }
}

And this class (within the same script) representing a weapon:

public class Weapon
{
    //properties here
}

Now, when I try to reference weaponsList to get List.Count using this code (from a different script), it throws a NullReferenceException, saying Object reference not set to an instance of an object:

Ship ship = GameObject.Find("Player").GetComponent<Ship>();
if (ship.weaponsList.Count >=2)
{
    //do stuff
}

But any other property of ship i try to access works just fine. Can someone help? If you need additional context or code, please let me know and I'll make the necessary edits.

EDIT: The start method is special to Unity and is always called by default when the script initializes.


Solution

  • To avoid this error Add constructor to your class

    public class Ship : MonoBehaviour 
    {
        public Ship()
        {
             weaponsList = new List<Weapon>();
        }
        public List<Weapon> weaponsList;
    
        void Start()
        {
            weaponsList = new List<Weapon>();
            weaponsList.Add(new Weapon());
            weaponsList.Add(new Weapon());
        }
    }