Problem with reading values from scripts on GameObjects in Lists
Hi, I am having a problem with reading values from scripts on GameObjects which are stored in Lists. What I am trying to accomplish is the following:
The game I'm making is a small turn based strategy-game in which you conquer territory. It revolves around the GameAction GameObject. This contains a script which has some values, most importantly a selectedTerritory GameObject and a targetTerritory GameObject.
During a player turn, a player can select a friendly territory and rightclick an enemy territory. This triggers the creation of a new GameAction GameObject:
newAction = gameAction;
newAction.GetComponent<GameAction>().currentAction = GameAction.typeOfAction.Attack;
newAction.GetComponent<GameAction>().selectedTerritory = selectedTerritory;
newAction.GetComponent<GameAction>().targetTerritory = targetTerritory;
gameActionList.Add(newAction);
Then, at the end of the turn, I want to read all the information from all the stored GameAction GameObjects.
public void ResolveGameActions()
{
gameActionsToBeResolved = mapManager.GetComponent<MapManager>().gameActionList;
foreach(GameObject gameAction in gameActionsToBeResolved)
{
Debug.Log(gameAction.GetComponent<GameAction>().targetTerritory.name);
}
}
I expected this method to return all names of targetTerritories the player selected during play. However it only returns the name of the last selected targetTerritory 5 times. To me it seems that all GameActions im creating are the same: but I'm not sure how to do it otherwise. Any help would be greatly appreciated.
It always returns the same thing 5 times no matter if the player selects ANY number of things, or returns the last one 5 times if the player selects 5 things? EDIT: Are you sure that your selectedTerritory variable in the $$anonymous$$ap$$anonymous$$anager is being altered when the player tries to select something?
Answer by NoseKills · Mar 08, 2016 at 04:27 PM
Doing this newAction = gameAction;
doesn't create anything new. It just assigns a reference pointing to "gameAction" object into a new variable.
If this truly is all the relevant code and you are not creating new instances of GameAction class anywhere, then you are just putting the same object in the list over and over and changing the values in this one object.
Since GameAction is a MonoBehaviour, to create a new instance of GameAction you would have to do something like
newAction = new GameObject("action").AddComponent<GameAction>;
...
If it was a normal class, you'd use the new keyword and call the constructor to directly make new instances.
newAction = new GameAction();