I'm trying to learn how to count enemies and remove them from a list if they die.
so i have this script which essentially counts the amount of enemies at void start()
the issue i'm having though is: when i call the method from a script which removes an enemy from the list i get a Null reference exception error.
this is the method i'm trying to call
public void KilledEnemy(GameObject Enemy)
{
if (Enemies.Contains(Enemy))
{
Enemies.Remove(Enemy);
}
Debug.Log(Enemies.Count + " Enemies Left");
}
for clarification this is the code with the list.
public class Level1Control : MonoBehaviour
{
public GameObject Exit;
public List<GameObject> Enemies = new List<GameObject>();
public static Level1Control instance;
// Start is called before the first frame update
void Start()
{
Enemies.AddRange(GameObject.FindGameObjectsWithTag("Enemy"));
Debug.Log(Enemies.Count + " Enemies Left");
}
public void KilledEnemy(GameObject Enemy)
{
if (Enemies.Contains(Enemy))
{
Enemies.Remove(Enemy);
}
Debug.Log(Enemies.Count + " Enemies Left");
}
public bool AreOpponentsDead()
{
if (Enemies.Count <= 0)
{
return true;
}
else
{
return false;
}
}
private void Update()
{
AreOpponentsDead();
if (AreOpponentsDead() == true)
{
OpenDoor();
Debug.Log("Dead");
}
}
public void OpenDoor()
{
}
}
the way i attempt to call the function is like this (this is the entirety of the code in this script:
public GameObject thisEnemy;
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("Bullet"))
{
Level1Control.instance.KilledEnemy(thisEnemy);
this.gameObject.SetActive(false);
}
}
any help is greatly appreciated.
Edit
ok so thanks to the wonderful people who took the time out of their day to help me the problem was solved!
i added this to my level1control script:
private void Awake()
{
instance = this;
}