[SOLVED]c# Help With List/Array System

I am not what you would call an “Expert” at c# but I still somewhat know what I am doing. I am creating a game where there are 30+ characters that you can have on your party but only a max of 10 at a time(Kinda like Fire Emblem). I want to be able to create a system so the game knows what 10 characters to instantiate after I switch from the character selection scene and into the level. I was thinking of using a tag system so when a character is selected it would assign them a tag “CharacterOne - CharacterTen”. I know that part is easy but the part that I am stumped on is when a character is deselected, every character under it would shift to the tag with the lowest available number(for example if I had 10 characters selected and I remove Character6 from the list, Character7 would shift down to fill the Character6 slot and so on).

Rough Example Code c#:

void Update(){
if(){//Check to see if character is removed
//shift Tags
}

public void CharacterOne(){ //Preform when UI button is clicked
//change Tag from “Inactive” to the next available character tag
}
}

As you can see I am not very sure as to what to do after this point so some help would be appreciated.

tags? sounds more like a job of a 10 slot array list if you want it to change shape…

1 Like

I am open to any kind of revision. If you think an array would work then I am listening. I have thought of using an array but I am not very good/efficient at using them.

Yeah, tags are a terrible solution for this. Here’s a little snippet to get you started with a List-based solution - start with this and see how much you can work out, I assume there will be more questions as you work on this.

using System.Collections.Generic; //at the top of your script

...
List<GameObject> activeCharacters; // probably better if it's List<SomeCharacterScriptName>
void Start() {
activeCharacters = new List<GameObject>();
//populate your list using repeated activeCharacters.Add(someCharacterObject);
}
//called from your UI button
public void RemoveCharacter(int index) {
activeCharacters.RemoveAt(index);
}
1 Like

I am sorry but could I get some further explanation on how the list works. I don’t think I have messed with them before. Also completely off topic, what is your deal with GameObject.Find? I have a few scripts littered with it.

It’s slow.
It’s also arbitrary, in that it just picks the first thing out there that exists with that name.

As for a List, it’s like an array. But resizes. When you remove an element from a List, all elements ahead of it shift back to take up the empty space.

It essentially, acts like a List. Hence its name.

Just like what you asked for.

How can I add a limit of 10 to the list?

Note how StarManta’s class has a ‘RemoveCharacter’ method. Well implement other methods like ‘AddCharacter’ and the sort.

From outside the class, you don’t ever directly access the list, but instead acccess these methods. And when AddCharacter is called, you test if there are already 10 characters and don’t allow any more to be added.

Programming is pretty straight forward… you don’t want to allow something, but a test in, and don’t allow it.

1 Like

This is what I am looking at right now.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SelectCharacters : MonoBehaviour {

    private bool active1;

    private int characterLimit = 0;

    public GameObject CharacterOne;
    public GameObject CharacterTwo;


    List <GameObject> activeCharacters;

    // Use this for initialization
    void Start () {
        //CharacterOne = GameObject.Find ("CharacterOne");
        activeCharacters = new List<GameObject> ();
    }
  
    // Update is called once per frame
    void Update () {
  
    }

    public void AddRemoveCharacterOne(int index){
        active1 = !active1;
        if (characterLimit < 10) {
            if (active1) {
                activeCharacters.Add (CharacterOne);
                characterLimit ++;
                Debug.Log ("Character 1 Added");
                Debug.Log("Characters Selected: " + characterLimit);
            } else {
                activeCharacters.RemoveAt (index);
                characterLimit --;
                Debug.Log (index + "Remvoved");
                Debug.Log("Characters Selected: " + characterLimit);
            }
        }
    }

    public void AddRemoveCharacterTwo(int index){
        active2 = !active2;
        if (characterLimit < 10) {
            if (active2) {
                activeCharacters.Add (CharacterTwo);
                characterLimit ++;
                Debug.Log ("Character 2 Added");
                Debug.Log("Characters Selected: " + characterLimit);
            } else {
                activeCharacters.RemoveAt (index);
                characterLimit --;
                Debug.Log (index + "Remvoved");
                Debug.Log("Characters Selected: " + characterLimit);
            }
        }
    }
}

I am not sure if it is removing correctly but the debug is coming through.

Fundamentally, my problem is that it’s never the best solution to any given problem in a game. There’s always something that is better, cleaner, and more reliable. The only trick really is that to implement the better solution, you have to know which of the 5+ alternate methods is the one you actually want to use in a given situation.


Let's go ahead an add a script to your characters, let's call it CharacterScript for now. That script will contain a lot of information within itself, so that you don't have to keep track of it in your main script - this is going to save you a LOT of copying and pasting. Anytime you find yourself making variables or functions like CharacterOne/CharacterTwo/etc, STOP, that is the wrong answer. You can use an array, and/or move those properties into their own class. In the case of functions, you should use a parameter as an index like the AddCharacter function in my code snippet does. (Note that Unity UI buttons can be set up to call functions with parameters like this!)

So for starters, CharacterScript will contain a 'characterActive' bool. This one variable, in multiple places, will replace active1, active2, etc.

Second bit of advice: activeCharacters.Count will give you the number of items in the list. characterLimit should remain constant at 10.

Third: your functions, as they are now, will be prevented from *removing* objects when you have 10 items in the list, you don't want that!

Each of my characters has their own personal variation of a script script similar to this already attached to them. Would this be a good place to store the information you are talking about?

using UnityEngine;
using System.Collections;

public class MainCharacter : MonoBehaviour {

    private int strength;
    private int magic;
    private int agility;
    public int speed;
    private int defense;
    private int luck;

    void Update(){
        strength = GameInformation.Strength;
        magic =  GameInformation.Magic;
        agility = GameInformation.Agility;
        speed = GameInformation.Speed;
        defense = GameInformation.Defense;
        luck = GameInformation.Luck;
    }
}

Earlier I wrote this little script on another thread that could help you:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectTracker : MonoBehaviour
{
     static List<GameObject> emptyList = new List<GameObject>();
     static Dictionary<string, List<GameObject>> collection = new Dictionary<string, List<GameObject>>();
     public string tag = "myTag";
     void Awake()
     {
          if (!collection.ContainsKey( tag ))
              collection[tag] = new List<GameObject>();
          collection[tag].Add( gameObject );
     }
     void OnDestroy()
     {
          collection[tag].Remove( gameObject );
     }
     public static List<GameObject> GetObjectsWithTag( string tag )
     {
          return collection.ContainsKey( tag ) ? collection[tag] : emptyList;
     }
 
     public static void Enumerate( string tag, System.Action<GameObject, int> callback)
     {
          if (!collection.ContainsKey( tag ))
               return;
          List<GameObject> list = collections[tag];
          for (int i = 0; i < list.Count; i++)
          {
               if ( callback != null )
                    callback( list[i], i);
          }
     }

     public static void Enumerate<T>( string tag, System.Action<T, int> callback)
     {
          if (!collection.ContainsKey( tag ))
               return;

          List<GameObject> list = collections[tag];
          for (int i = 0; i < list.Count; i++)
          {
               if ( callback != null )
               {
                    T component = list[i].GetComponent<T>();
                    if ( component != null )
                         callback( list[i], i);
               }
          }
     }
}

Add this little script to your GameObjects, add their respective tag (Player, Enemy, Neutral) via inspector/code, then you can get them via code like this:

void PrintAllCharacters()
{
     ObjectTracker.Enumerate( "Player", ( obj, i ) =>
     {
          Debug.Log("Player Army - "+ i +". "+obj.name);
     });

     ObjectTracker.Enumerate( "Enemy", ( obj, i ) =>
     {
          Debug.Log("Enemy Army - "+ i +". "+obj.name);
     });

     ObjectTracker.Enumerate( "Neutral", ( obj, i ) =>
     {
          Debug.Log("Neutral Army - "+ i +". "+obj.name);
     });
}

It can come in handy to keep them all at one place. You don’t even have to worry about adding/removing them; when you Instantiate or you add the little component they will get added to the List and removed when Destroyed.

Do note however, they will be added into the List next frame during the Awake() method.

Also, there is certainly room for improvement, like adding enum tags instead strings, but I can leave that up to you to customise to your needs :slight_smile: Hope it helps!

Except for the ‘personal variation’ bit, it would - this should be the same script on all 10 characters.

you mean all 30+ when I get that far? Ok less work if I just make one universal script. So what do I need to put in it?

Yeah, using components you should strive to use generic scripts that can be modified within inspector instead subclassing them.

The following is a bad example:

public class ChromCharacter : MonoBehaviour
{
     public int strength = 10;
     public int magic = 7;
     public int agility = 5;
     public int speed = 12;
     public int defense = 8;
     public int luck = 4;
}

public class FrederickCharacter : MonoBehaviour
{
     public int strength = 14;
     public int magic = 4;
     public int agility = 7;
     public int speed = 14;
     public int defense = 12;
     public int luck = 5;
}

You should instead create a generic class:

public class CharacterSheet : MonoBehaviour
{
     public int strength;
     public int magic;
     public int agility;
     public int speed;
     public int defense;
     public int luck;
}

And populate their values within Unity inspector on that gameObject. It will make your life easier and code reusable.

1 Like

I was originally going to do that but I have all of my character data in a script called GameInformation which allows me to pull whatever I need and use it where ever

Yeah, I noticed you used that GameInformation, but forgot to mention. I’m not sure if that is the wisest way to approach this problem. Every gameObject should contain its own data.

void Update(){
        strength = GameInformation.Strength;
        magic =  GameInformation.Magic;
        agility = GameInformation.Agility;
        speed = GameInformation.Speed;
        defense = GameInformation.Defense;
        luck = GameInformation.Luck;
    }

If all of your scripts contain this in Update(), won’t they all change their stats to the one you set (each frame)? I’m afraid this will cause you a lot of problems later on as you develop your project.

I am just using a generic name for the stats right now later on I will change from “strength = GameInformation.Strength” to “strength = GameInformation.nameOfCharacterStrength” and that is why they all have their own scripts,

You need to use Polymorphism for this stuff. I see where you are starting down the road of thinking… Everyone needs to have similar stats, but everyone needs to be different. Polymorphism does that.

using UnityEngine;
using System.Collections;

public class Character : MonoBehaviour
{
    public string name = "Generic Character";
    public int strength = 5;
    public int magic = 5;
    public int agility = 5;
    public int speed = 5;
    public int defense = 5;
    public int luck = 5;
    public int health = 30;
    public int healthMax = 30;

    public bool isDead { get { return health <= 0; } }

    public virtual void Damage(int amount) {
        health -= amount;
    }

    public virtual void Heal(int amount){
        health += amount;
        if(health > healthMax) health = healthMax;
    }

    public virtual void Attack(GameObject other){
        // do attack stuff here.
    }
}

So now look at Chrom:

using UnityEngine;
using System.Collections;


public class Chrom : Character
{
    public override void Attack(GameObject other){
        // do special Chrom attacks here.
    }
}

and Fredrick:

using UnityEngine;
using System.Collections;

public class Fredrick : Character
{
    public override void Heal(int amount){
        health += (int)((float)amount * 0.5f);
        if(health > healthMax) health = healthMax;
    }

    override void Attack(GameObject other){
        // do special Fredrick attacks here.
    }
}

Using Character as a base class means that in other code, all you have to say is something like this…

bob.Attack(bill);

Since Bob is a Character, he always has the Attack method.

chrom.Heal(2)

Since chrom (which is the class of Chrom) extends Character, then he also has the heal method.

Unfortunately, in Unity it is better to assign stats via Inspector rather inheritance, you have less scripts and you can use same Character script on 100+ prefabs for each character. Polymorphism is generally considered bad for describing GameObjects, one should prefer “Composition over inheritance”.