Creating a faction list and their enemies

Hello,

I am making an AI, and I would like for them to have their own faction that the AI belongs to, and then get a list of the factions that faction are to attack.

Currently I’ve tried using enums, but I cannot figure out how to traverse the enum to get it’s values in a loop.

Any suggestions? Cheers

Here is how you iterate an enum in C#:

// This is your enum
enum myEnum
{
    elem1,
    elem2,
    elem3
}
// .... here is the iteration
foreach (myEnum i in Enum.GetValues(typeof(myEnum)))
{
    //..
}

cheers! I Googled for it, and I got a whole bunch of results like thes, but none worked. Thankfully this one does! You’ve saved me twice now!

Okay, now my issue is finding the best medium for holding the list/array of their enemies. Arrays seem to give me an error

NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)

when I try to:

int c = 0;
foreach (CapEnemies i in Enum.GetValues(typeof(CapEnemies)))
{
EnemyFactions

 = i.ToString();
				c++;
			}

and lists, I can't seem to add to it, as it keeps saying that it's never assigned a variable....

You should post your complete code, I don’t know how you’re declaring and using the array.

I was thinking to something like:

Array capEnemies = Enum.GetValues(typeof(CapEnemies));
string[] EnemyFactions = new string[capEnemies.Length];
int c = 0;
foreach (CapEnemies i in capEnemies)
{
    EnemyFactions[c++] = i.ToString();
}

cheers again, that worked. I was using a List and string[ ] and they weren’t working. But now all is well! Hopefully one day I can help you for once! I’m making up quite the tab!

You’d want something like this for a List…

Array capEnemies = Enum.GetValues(typeof(CapEnemies));
List<string> EnemyFactions = new List<string>();
foreach (CapEnemies i in capEnemies)
{
    EnemyFactions.Add(i.ToString());
}

You’re welcome :wink: The difference between string[ ] and List is just that using string[ ] you must know the length of the array when you initialize it (new string[XXX]) while with List you don’t need to know how many items it will contains because you will use Add() to increment its capacity. But if you know how many items there are and the capacity will never change, then it is usually better to use a fixed array (like your case, since an enum will never change its length).