Good day everyone. I’m new on unity. I’m trying to create a “light gun shooter” game. I have 17 positions where enemies may apear and a List to save each enemy instanciated by a prefab. The problem is that when I try to delete the GameObject of the list it seems to be out of the range. I’ve been trying and it looks like the GameObject is not correctly being added to the List. This is part of my code from the EnemySpawner:
public class EnemySpawner : MonoBehaviour
{
public GameObject enemy;
public GameObject enemySpawner;
public Vector2[] position;
List<GameObject> enemies = new List<GameObject>();
static int enemiesCount = 0;
bool existGO = false;
int randomPos;
float nextSpawn = 4f;
void Update()
{
if (Time.time > nextSpawn)
{
if (nextSpawn <= 15)
{
nextSpawn = Time.time + Random.Range(2f,3f);
} else if (nextSpawn > 15 && nextSpawn <= 30)
{
nextSpawn = Time.time + Random.Range(1.5f,2.5f);
} else
{
nextSpawn = Time.time + Random.Range(0.7f,1.7f);
}
randomPos = Random.Range(0,(position.Length - 1));
for (int i = 0 ; i < enemiesCount ; i++)
{
if (enemies*.transform.position == new Vector3 (position[randomPos].x,position[randomPos].y,0))*
{
existGO = true;
}
}
if (existGO == false)
{
GameObject myEnemy = Instantiate(enemy);
myEnemy.transform.SetParent(enemySpawner.transform, false);
myEnemy.transform.position = new Vector3(position[randomPos].x, position[randomPos].y, 0);
enemies.Add(myEnemy);//This Seems Not To Be Working Well
enemiesCount += 1;
Debug.Log(enemiesCount); //Works fine
existGO = false;
}
}
}
public void RemoveEnemy(GameObject enemigo)
{
Debug.Log(enemies[0].transform.position);//Out Of Range
for (int i = 0 ; i < enemiesCount ; i++)
{
Debug.Log(enemies*.transform.position);//Out Of Range*
if (enemies*.transform.position == enemigo.transform.position)//Out Of Range*
{
enemiesCount -= 1;
enemies.RemoveAt(i);
Destroy(enemigo);
}
}
}
}
Thanks to everyone who can help me.