- Home /
Why is transform.position of a prefab that's been instantiated different than a gameobject created on the scene, when they are in the exact same position?
So I've been working on a game which requires different platforms to instantiate in the correct position (in order to connect each platform's path). However, whenever I instantiate a platform from the prefab to a child location of another platform prefab, they don't match. So I tried to figure out why, by simply creating a plane (set the scale to (1,1,2)), and drag it to the prefab folder and delete it off the scene. Created an identical plane on the scene positioned at (0,0,0). Finally attached this script to an empty object on the scene set at (0,0,0).
public Transform platformPrefab;
public Transform onScenePlatform;
void Start () {
Invoke ("Spawn", 0f);
}
void Spawn () {
Instantiate (platformPrefab, Vector3.zero, Quaternion.identity);
print (platformPrefab.transform.position);
print (onScenePlatform.transform.position);
}
Here's the result: platformPrefab.transform.position = (-1.7,28.3,4.9), but the Inspector shows (0,0,0). onScenePlatform.transform.position = (0,0,0). In the scene (during play), both identical platforms are placed right on each other. What is going on? Where did the platformPrefab.transform.position's vector come from? Thank you for reading this.
Answer by HammerCar · Jun 19, 2015 at 07:24 PM
In the platformPrefab prefab you probably have the position (-1.7,28.3,4.9) but if you instantiate the prefab it creates a copy of it and set its position to Vector3.zero its in the center of your scene. So when you are trying to read its position, you are actually reading the prefabs position, not the instantiated one. If you want to read the real position you can do something like this.
public Transform platformPrefab;
public Transform onScenePlatform;
void Start () {
Invoke ("Spawn", 0f);
}
void Spawn () {
GameObject platform = (GameObject)Instantiate (platformPrefab, Vector3.zero, Quaternion.identity);
print (platform.transform.position);
print (onScenePlatform.transform.position);
}
Here it is reading the instantiated position. If you want to instantiate it to the same position as the prefab, you can change the "Vector3.zero" to "platformPrefab.transform.position". If you want some other position you can do "new Vector3 (x, y, z)". x, y and z are your x, y and z positions.