Hi there,
In my project I have a central empty object called Game which contains several game objects that interact together as children. I am trying to position one particular child in the top left of the screen along with all of its children after instantiating it.
To do this I am doing the following in Game
GameObject child = Instantiate(childReference, new Vector3(0, 0, 0), Quaternion.identity);
child.transform.parent = transform;
Vector3 cameraPoint = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 10));
child.transform.position = cameraPoint;
This successfully moves the child where I am expecting it to but all the children of GameObject created are offset the amount moved so that they remain at the original 0,0,0 position.
Any Ideas?
Thanks
Solution found!
Turns out you have to use a transform.localPosition otherwise the position is placed in global coordinates
Sort of something weird I found. This problem occurs only if I instantiate the child and its respective children at run time.
If I add the object child and its children to the hierarchy in the inspector and run the same program with a reference to the child rather than the Instantiated object the child and respective children all move uniformly as expected.
Here are some photos of my process and the direct code.
In this photo above I placed FullDeck as a child of Game before running the program, when the following code ran the results were as expected where just the coordinates of FullDeck were changed and none of its children cards moved
public GameObject fullDeckRef;
public GameObject emptyDeckRef;
public GameObject fullDeck;
// Start is called before the first frame update
void Start()
{
float xOffset = 1f;
float yOffset = 3.111111f / 2f+1;
Vector3 cameraPoint = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 10));
Debug.Log(cameraPoint);
cameraPoint.x -= xOffset;
cameraPoint.y -= yOffset;
fullDeck.transform.position = cameraPoint;
}
I then got rid of FullDeck and changed the code to have the following two lines which instantiates the FullDeck and its children from the reference.
public GameObject fullDeckRef;
public GameObject emptyDeckRef;
public GameObject fullDeck;
// Start is called before the first frame update
void Start()
{
float xOffset = 1f;
float yOffset = 3.111111f / 2f+1;
fullDeck = Instantiate(fullDeckRef, new Vector3(0, 0, 0), Quaternion.identity);
fullDeck.transform.parent = transform;
Vector3 cameraPoint = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 10));
Debug.Log(cameraPoint);
cameraPoint.x -= xOffset;
cameraPoint.y -= yOffset;
fullDeck.transform.position = cameraPoint;
}
This then produced the following result
In this instance FullDeck is at the same position, 8.0, 3.4, but in this second case all of the FullDeck’s children have been set to position -8.0,-3.4