- Home /
Cant use foreach loop on my custome class
i am Trying to make a custom class, to arrange the wave of enemies more simple, so my class will set the enemies health,gold and it will be different for each wave. so i can modify and manage my enemies more properly, but i get an error and i dont know how to fix it. Here is my Code.
public class GameManagerScript : MonoBehaviour {
// Created a Custom Class to make each wave different
[System.Serializable]
public class EnemyManager {
public GameObject enemy;
public int maxEnemies;
public float timebetweenspawns = 1.5f;
public int EnemyGold;
public int EnemyCurrentHealth;
}
public List <EnemyManager> EnemySpawn = new List<EnemyManager>();
[SerializeField]
private Transform SpawnPoint;
private int waveLevel;
private int totalSpawned = 0;
private int AliveEnemies;
private int enemiesIndex;
private bool EnemiesNumeratorActive = false;
[SerializeField]
private int CurrentGold;
void Start () {
UIText = FindObjectOfType<Text> ();
EnemyHealth enemyhealth = gameObject.GetComponent<EnemyHealth> ();
foreach (EnemyManager enemies in EnemySpawn[enemiesIndex].enemy) {
enemyhealth.AddHealth (EnemySpawn [enemiesIndex].EnemyCurrentHealth);
}
Answer by moltow · Aug 05, 2017 at 10:33 PM
I believe what you want is:
foreach (EnemyManager enemy in EnemySpawn)
{
enemyhealth.AddHealth(enemy.EnemyCurrentHealth);
}
The object reference not set to an instance of an object is likely because you're not populating your List. If your enemy GameObjects all have the same tag (e.g., "enemy"), then you can use GameObject.FindGameObjectsWithTag to populate your list.
So how my code should be. By finding the health script from each Enemy object in the list and add the EnemyCurrentHealth.
sorry i am a bit new to unity
Well I don't really know enough about your other classes to know that this is completely correct and I don't know the signature of your AddHealth method. Having said that, I would guess it would be something like this:
void Start ()
{
UIText = FindObjectOfType<Text>();
EnemySpawn = GameObject.FindGameObjectsWithTag("Enemy");
foreach (Enemy$$anonymous$$anager enemy in EnemySpawn)
{
EnemyHealth enemyhealth = enemy.GetComponent<EnemyHealth>();
enemyhealth.AddHealth(enemy.EnemyCurrentHealth + 5);
}
}
Answer by karaflito · Aug 05, 2017 at 11:50 PM
unfortunately it doesnt work, it says, " object reference not set to an instance of an object"
what i want to do is to take the Enemy gameobject reference from the custom class and get its component and then send the currenthealth to that object.
so i try to use foreach loop to get every single enemy object from the list and add the health accordingly
Your answer
Follow this Question
Related Questions
Help With Add and Remove on a loop 2 Answers
"for" loop - DrawTexture problem. 0 Answers
problem with loop and mesh values 0 Answers
Crash on loop using Lerp. 1 Answer
Spawn Object 1 Answer