Updating values on one object update the values on all objects

I’m making a game where you control a team of soldiers. Each soldier is a script object that contains data about it.

public class Soldier {
  public int maxHealth;
  public int currentHealth;
  public int power;
}

Everything works fine if I have a team of several different units. However, if my team is made up of multiples of the same unit, I run into an issue. When you update a value, it updates it for all instances of that unit.

Are there any steps I can go through to troubleshoot this issue?

We’re going to need to see more of your setup. But, assuming you have say… 3 soldiers and each soldier has a “SolderStat” class for example which had a Soldier variable on it, changing the value of maxHealth of one of those Soldier variables will not effect the other based on what little info you’ve shown.

As for troubleshooting, you need to look at what you are trying to modify. Where are your instances of Soldier at? What are you actually targeting when you change a value on Soldier.

The instances are held in an array, and assigned as such:

public static bool AddUnit(Soldier soldier = null, int opening = -1) {
        // If no index is passed, find open slot
        if (opening == -1) {
            for (int i = 0; i < Party.Length; i++) {
                if (Party[i] == null) {
                    opening = i;
                    break;
                }
            }

            if (soldier == null) {
                return opening != -1;  // Check and return if space is available
            }
        }
      
        // If index is passed or space is open
        Party[opening] = soldier;
        return true;
    }

I was trying to have the function serve two purposes, but this is the basic methodology. I then access them by index. Space 0 is the one that is most frequently accessed, as it is the lead in battle. However, changing the health of space 0 changes the health of the rest of the same-type units in the party.

Never mind, I realized the issue. I’m creating the objects before assigning them, so I’m literally assigning the same object to multiple slots…

Seems the easiest way to help people is to wait 30 mins for them to figure it out for themselves!..

Sometimes a nudge or a second pair of eyes helps get a person back on the right track. It happens to a lot of developers, especially if you’ve been typing code all day long.