Hey listen, I have been trying to create an “enemy spawner” by making a list. But for some odd reason, the script doesn’t detect the variables from the “Public Class”. The program just says that they don’t exist even though they clearly do. Please Help.
private Vector3 spawnPosition;
public List<Monsters> enemies;
[System.Serializable]
public class Monsters
{
public GameObject Enemy;
public int counter;
}
void Start()
{
Spawn();
}
void Spawn()
{
for(int i=0; i<counter; i++)
{
spawnPosition.x = Random.Range(100, 100);
spawnPosition.y = Random.Range(100, 100);
Instantiate(Enemy, spawnPosition, Quaternion.identity);
}
}
,
I think I see the issue here. The variables you’re trying to access, Enemy and counter, are properties of your Monsters class, which is the type of your enemies list. But in your Spawn method, you’re trying to access them as if they were properties of the containing class. Instead, you should be iterating through the enemies list and spawning each enemy.
Something like this (Warning untested):
void Spawn()
{
foreach (Monsters monster in enemies)
{
for(int i = 0; i < monster.counter; i++)
{
spawnPosition.x = Random.Range(100, 100);
spawnPosition.y = Random.Range(100, 100);
Instantiate(monster.Enemy, spawnPosition, Quaternion.identity);
}
}
}
In this corrected version, we’re using a foreach loop to iterate through each monster in the enemies list, and then a for loop to spawn the number of each monster specified by the counter property. We’re also using monster.Enemy to instantiate the correct GameObject.
Let me know if this gets you closer to an answer.