Unable to change postion after instantiation of a prefab

Hello Community,

I created a simple project to illustrate my problem:

  • It’s an empty project with only one camera at postion (0,0,-10) and an empty game object named “Container” at position (0,0,5)
  • I have a prefab (named Parent) with two children GameObjects (childA and childB)
  • I have the following script attached to the Camera
using UnityEngine;

public class Crator : MonoBehaviour {

  public GameObject prefab;
  public GameObject container;

    void Update () {
    if(Input.GetKeyDown(KeyCode.A)) {
      var go = Instantiate(prefab, container.transform);
      SetLocalZ(go.transform);
      SetLocalZ(go.transform.Find("ChildA"));
      SetLocalZ(go.transform.Find("ChildB"));
      container = go;
    }

    if(Input.GetKeyDown(KeyCode.S)) {
      var go = Instantiate(prefab, container.transform);
      SetToParentZ(go.transform);
      SetToParentZ(go.transform.Find("ChildA"));
      SetToParentZ(go.transform.Find("ChildB"));
      container = go;
    }

    if(Input.GetKeyDown(KeyCode.L)) {
      foreach(Transform t in GameObject.Find("Container").GetComponentsInChildren<Transform>()) {
        Debug.Log($"{t.name} - {t.position.z}");
      }
    }
    }

  private void SetLocalZ(Transform t, int z = -1) {
    var pos = t.localPosition;
    pos.z = z;
    t.localPosition = pos;
  }

  private void SetToParentZ(Transform t, int z = -1) {
    var pos = t.position;
    pos.z = t.parent.position.z + z;
    t.position = pos;
  }
}

My issue:
After starting the scene, all the newly created GameObjects (after pushing A or S) have the same z coordinate (-1) according the editor (see picture bellow), but the log shows that the GameObjects have the expected coordinates (see second picture bellow).

Could you please tell me what cause the discrepancy, and how can I overcome it?

Thanks

3829666--323041--zlog.png

This happens because the editor only shows the ‘local’ position of an object and not the ‘world’ position. The local position of a child object might be 0,0,1 and the parent position might be 10,10,10 which would make the world position of the child equal to 10,10,11.

If you want to get or set the world position you can use transform.position instead of transform.localPosition

1 Like

Thanks, that all make sense.

Protip: If you put the inspector in debug mode it shows world position regardless of parents.