Reputation: 1901
I have set the parent of a HUD camera's transform to the transform of the object it's 'orbiting'. The trouble is, when I then set the position of the child transform, it is still being moved to 'global' coordinates.
I have tested this in the Unity editor, paused the game, and the HUD camera is, indeed, a child of the parent object (it is listed under that object's hierarchy).
The Unity tutorial here...
https://unity3d.com/learn/tutorials/topics/interface-essentials/hierarchy-and-parent-child-relationships
...seems pretty clear that, once an object is made a child of another, its position is relative to the parent object (from about 45 seconds into the video). But is there a difference between doing this programmatically and manually in the Unity editor?
Here's my relevant code:
hudCamera.transform.parent = hudSelectedObject.transform;
hudCamera.transform.position = new Vector3(0, 0, -50); // this still moves the HUD camera to global position 0, 0, -50 - why?
The parent object is not positioned at 0, 0, 0, so it's not just that the child object position is set relative to 0, 0, 0.
So how do I programmatically set the position of the HUD camera so it is relative to the parent transform position, if not by just setting it as a child of the parent object and then setting its position? Thanks.
Upvotes: 1
Views: 12810
Reputation: 343
Whenever you instantiate UI Item programmatically. Whenever I add any UI item through code. I use following code (updated it for your use)
hudCamera.transform.SetParent(hudSelectedObject.transform);
hudCamera.transform.localScale = Vector3.one;
hudCamera.GetComponent<RectTransform>().sizeDelta = Vector2.zero;
Upvotes: 0
Reputation: 10750
Instead of hudCamera.transform.parent = hudSelectedObject.transform;
Use this :
hudCamera.transform.SetParent(hudSelectedObject.transform);
hudCamera.transform.localScale = Vector3.one;
hudCamera.transform.localPosition= Vector3.zero; // Or desired position
Upvotes: 3