How to duplicate values from one component into another?

Hey :slight_smile:

I have a list of characters where I store character stats:

Character playerInList = GS.Instance.characterList[GS.playerIndex].GetComponent<Character>();

I have a bunch of these characters, and the component contains things like this:

public int Level = 1;
public int Health = 50;
public int Strength = 10;

To make this easier to access in the game, I instanciate the game object, like this:

playerGO = (GameObject)Instantiate(GS.Instance.characterList[GS.playerIndex]) as GameObject;
playerGO.name = "PlayerGO";
player = playerGO.GetComponent<Character>();

So, I get a copy of the fields, and it’s easy to manipulate in the game, using player.Health = 12;

However, when the player dies, or when the player exits, or has finished the level, I want to save the character back to the original one.

I hoped this would work:

charInList = player

but, it does not.
I know of two other possibilities:

  1. Just copying all the fields from player, into charInList, like so. charInList.Health = player.Health.

But this can get somewhat complicated and error prone.

  1. Destroying charInList GameObject, and Instanciating player gameobject.

But if there are other better ways, it would be great to hear about it :slight_smile:

Thanks a bunch!

Edit: Destroying the gameobject inside the list, and instanciating a copy from the player gameobject into the list again seems to work ok.
Is this fine to do?

Kjetil

Try using playerprefs, before player dies (or at checkpoints) save a playerprefs line and then call it back and convert it back into an int to be used throughout the level as you’re doing. This works for exiting as well, and you can keep as many playerpref entries as you want for any level (max 1mb for web player through).

yep, I use playerprefs for saving the characters, and I’ll also use it to save checkpoint. But I figured it would be better to copy values directly since the two scripts I am copying between are still “alive”.

I maintain a list of the characters, and then I have that 1 activeplayer, which is a copy of one of the characters in the list. So, currently, when I save, I just save all characters in the list. So, you see, I need an easy way to copy changes that happened to the activeplayer back into the saving list.

It could be that I have just designed this poorly and need to think a bit new. Thanks a lot for the input though, playerprefs are quite neat to use. :slight_smile:

Kjetil