How to recalculate the position of an object when adding using Instantiate? (Unity)

59 Views Asked by At

I'm completely confused about the local and world coordinates of objects. I have a hierarchy of objects like this:

enter image description here

I add LeftTargetPrefab with the previously saved position (for example Vector3(10f, 10f, 10f)) to BallsPath and it is set correctly. But if I try to add LeftTargetPrefab to BallTargets, then the position is also set to Vector3(10f, 10f, 10f). If, while starting the game, I create a clone of LeftTargetPrefab and drag it into BallsTarget, the coordinates are converted to local coordinates correctly. How can I make sure that when adding to BallsTarget via Instantiate, the LeftTargetPrefab(Clone) position is immediately correctly recalculated to the local one?

1

There are 1 best solutions below

7
JanS On

Update after comments:

To instantiate the object relative to a new parent, use Instantiate(originalObject, parentTransform, false. This call uses the instantiateInWorldSpace boolean to set the Object's position relative to its new parent, see the below mentioned link.

Another thing: In your image, LeftTargetPrefab is a child of BallsPath. So it's coordinates are already not world coordinates anymore, but relative to its parent.


When you say "add LeftTargetPrefab with the previously saved position" does this happen from script during runtime?

You could try the instantiateInWorldSpace options of Object.Instantiate. For this you would instantiate via the parent Transform (BallsTarget in this case, I guess).

Another option would be to pass the parent's position and a possible offset in terms of local coordinates via the Transform.localPosition etc of the parent object.