Title explains what I’m trying to do. I know how to make lists, but I can’t seem to figure out how to make it so each item stores a range of variables.
The best example would be a list that stores enemies, and each enemy has something like:
float health = 20.5f;
int attack = 25;
bool isCursed = false;
Then I can just add more “enemies” to the list, but each enemy always has these 3 variables.
Could somebody help me out in letting me know how to do this?
[Serializable] public class Enemy
{
public float health = 20.5f;
public int attack = 25;
public bool isCursed = false;
}
Enemy e1 = new Enemy() { health = 10f, attack = 30, isCursed = true };
//you can modify it
e1.isCursed = true;
//you can make a list of them
List<Enemy> enemies = new List<Enemy>();
enemies.Add(e1);
enemies.Add(new Enemy() { health = 12f, attack = 25, isCursed = true });
// add a bunch of little guys in a loop
for (int i = 0; i < 10; i++) {
enemies.Add(new Enemy() { health = 1f, attack = 5, isCursed = true });
}
I added [Serializable] to the beginning of the class definition so that your enemies can be added and edited in the inspector.
This will work if the class inherits from MonoBehaviour. If not then you cannot do that, plus this logic would lead to errors with the list having null references. You should explicitly remove items from the list and then Destroy/delete/dereference them.
Ah, right, Destroy() is a wrong example of a method for this case. I was referring to methods that aren’t required to inherit from Monobehaviour, like Debug.Log, setting variables, etc.
In the end though your info is not wrong. All classes and even structs can have functions/methods in them to help make things easier. Its only that we have to watch how we make things easier and try to not introduce too many bugs that cause problems down the road.