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