I have a very simple script attached to a GameObject (GO1). It just calls a function that instantiates a new GameObject (GO2) and sets GO2 as a child of GO1.
For testing purposes, I have GO1 just instantiating prefab of itself. The issue is when I call GO2.transform.setParent, GO2 either shrinks in scale when I have worldPositionStays set false or gets massive if I set it to true.
The following code occurs in the original GameObject (GO1). Each child that gets instantiated runs the same code.
If worldPositionStays is false, each child object gets smaller and smaller with each instantiation. If true, each one gets bigger and bigger. The positions also change.
My goal is to have the child objects keep their original scale and position as before they were parented. I must be missing something here.
So I think this is what’s happening. I’m going to assume your base gameobject scale is something smaller than 1. So let’s say it’s Vector3(.5, .5, .5).
With worldPositionStays = false it adjust the child’s size based on the parents size. when you set a child with a .5 scale to a parent of .5 scale you now have a child with .5 * .5 = .25. So you have a parent gameobject at half, and a child of quarter. Do that again with another child and now you have .25 * .5 = .125.
With worldPositionStays = true it tries to adjust the child to stay it’s relative size. So instead it does something like this. Child = .5 scale. Parent = .5 scale. Now your scale is .5/.5 = 1 to make the child twice the size it was set to in order to overcome the half size of the parent to maintain the child’s size. The next child however is .5/.5/.5 = 2 and so on.
If that’s not exact then I think it’s pretty close to what’s happening.
Possible Solution
You could maybe overcome this by simply setting the worldPositionStays = false and manually calculating the scale of the child with something like 1/(parent scale) * (child scale) and then setting the child’s localPosition to Vector3.zero.
Another Possible Solution
Another way to get around this is to have empty game objects with a scale of 1 that hold the visual object. Then each instantiation is basically just an empty gameobject of scale 1 parented to another empty gameobject of scale 1 with each one simply having it’s own child with the visual component.
It was doing exactly what you said, which doesn’t seem right to me.
I still don’t understand why setParent is working this way. It seems to me that worldPositionStays = true should keep the object exactly the same as it was previously, including taking into account the scale/position of the parent.