- Home /
Script is reading from prefab instead of instance
I have a player Prefab with a few scripts attached to it. This prefab is instantiated 4 times from a for loop, each at its own location.
void InstantiateChar(int x, int y, string nome){
GameObject instance = Instantiate(player, new Vector3 (x, y, 0f), Quaternion.identity) as GameObject;
instance.GetComponent<CharacterTemplate>().namae = nome;
}
for (var i = 0; i < chars.Count; i++) {
InstantiateChar(chars[i].x, chars[i].y, chars[i].namae);
}
This is working perfectly, but, when I call a transform.position from a script attached to any instantiated player, even though in the inspector every player has a different position, the transform.position always returns the position of the prefab.
This is also true for other things like, I set the HP variable of one of the players to 0 (and the inspector reflects that), but when called from one of the scripts it always shows the prefab value.
How can I correct this and get the transform.position of the instance and not of the prefab?
Store a reference to the new objects when they are created.
Answer by JohnBartle · Mar 19, 2019 at 05:35 PM
It is difficult to determine without seeing the rest of your script but the issue seems to be with the arguments that are being passed in: chars[i].x, chars[i].y
I can't see what you are storing in chars[i].x and chars[i].y
Here is what I came up with:
public GameObject player;
public List<GameObject> chars;
void Start()
{
for (var i = 0; i < chars.Count; i++) {
Vector3 currentPosition = chars[i].transform.position
//OPTIONAL: Added a new argument, the transform of the gameobject the player will be instantiated ontop of,
//it will child the instantiated object to the gameobject in the scene
InstantiateChar(currentPosition.x, currentPosition.y, currentPosition);
}
}
void InstantiateChar(int x, int y, Vector3 currentPosition){
//player is already a gameobject, no need to assign the gameobject variable as a gameobject, just instantiate it.
Instantiate(player, new Vector3 (x, y, 0f), Quaternion.identity, currentPosition);
}