-1
    private EnemyShoot[] shoot;
    private List<EnemyShoot> shootList = new List<EnemyShoot>();

    void Start()
    {
        shootList.Add(shoot[0].GetComponent<EnemyShoot>());
        shootList.Add(shoot[1].GetComponent<EnemyShoot>());
    }

    void Update()
    {
        float angle = shootList[0].AngleTowardsPlayer();
        StartCoroutine(shootList[0].Spread(5, 10, angle, 1f, 5f, 3f, 1f));
        StartCoroutine(shootList[1].Spread(2, 5, angle, 0.6f, 10f, 1f, 0.6f));
    }

I'm getting an error saying "Object reference not set to an instance of an object" on line:

shootList.Add(shoot[0].GetComponent<EnemyShoot>());

What am I doing wrong?

vehz
  • 3
  • 2
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/q/4660142/1260204) – Igor Apr 13 '20 at 11:36
  • if shoot is an array of enemyshoot, you dont want to get component on it... it already is the component – BugFinder Apr 13 '20 at 11:36
  • I know very well what a NullReference exception is, and what's causing it. The problem here is I don't know what kind of logic/syntax error I did for the program to not be able to recognize the object. – vehz Apr 13 '20 at 16:38

1 Answers1

1

You must somehow initialize the array elements as well in order to invoke one of their methods. For example:

private EnemyShoot[] shoot = new EnemyShoot[] { new EnemyShoot(), new EnemyShoot() };

Or in the start() method:

public void Start()
{
    shoot = new EnemyShoot[] { new EnemyShoot(), new EnemyShoot() };
    shootList.Add(shoot[0].GetComponent<EnemyShoot>());
    shootList.Add(shoot[1].GetComponent<EnemyShoot>());
}

Or perhaps something more cleaner:

public void Start()
{
    shoot = InitializeEnemyShoots();
    shootList.Add(shoot[0].GetComponent<EnemyShoot>());
    shootList.Add(shoot[1].GetComponent<EnemyShoot>());
}

private EnemyShoot[] InitializeEnemyShoots()
{
    // write your initialization logic here
    return new EnemyShoot[] { new EnemyShoot(), new EnemyShoot() };
}
Alpha75
  • 2,140
  • 1
  • 26
  • 49