S.Y
S.Y

Reputation: 25

Unity can't have fixed localposition

I've created multiple game objects with each as previous object child, then change the local position also change the position related to the last object position, I want to have fixed local positions -0.2f, Thank you.

Vector3 spawnPosition = new Vector3(0, -0.2f, 0);

for (int i = 0; i < pooledAmount; i++)
{           
    GameObject obj = (GameObject)Instantiate(pooledObject, spawnPosition, Quaternion.identity);
    Transform t = obj.transform;
    t.parent = lastObject;
    lastObject = t;
    lastObject.transform.position = spawnPosition;
    lastObject.localPosition = new Vector3 (Random.Range(1,10),0,0);
}

Upvotes: 0

Views: 1257

Answers (1)

Thomas Finch
Thomas Finch

Reputation: 522

Position refers to it's global position, ignoring all parent transforms. LocalPosition refers to it's local position, relative to it's parent transform. So if you have ObjectA at x1, y2 and you child an ObjectB to it and give it a local position of x3, y5 then it's global position would be x4, y7.

If you want every spawned object's position to be completely unrelated to the other objects, then the best solution is to not child them to each other. Childing them to other spawned objects only results in their positions being relative to the other objects.

If for some reason you need them to be childed to other spawned objects, then you need to only set their transform.position and not their transform.localPosition. Keep in mind that moving one of them later will still change the position of child objects, however, so the first solution is still the best one. You might want to consider other ways to accomplish what you want without childing them to other ones.

Upvotes: 1

Related Questions