Change the rotation of a prefab after instantiating

Hi everyone, I’m wondering if it is possible to change the rotation of prefab already spawned.
thank you

Sure, you just need a reference to the object. If the rotation is triggered by some external action, like a collision or a raycast, then it will usually provide you with the reference. Otherwise Instantiate also returns the reference to the newly instantiated object, so you can save it for later use.

1 Like

yeah but at the satrt of the game I spawn 100 objects, depending if I type right or left I need to rotate all the spawned objects? do you have an idea? thanks

something like this

for (int i = 0; i < 100; i++) {
  GameObject go = Instantiate(prefab);
  go.transform.position = Vector3.Zero;
  go.transform.rotation = Quaternion.Euler(0,90,0);
}
1 Like

already tried but doesn’t work

Doesn’t work how?
@Siccity 's post would be the exact solution to rotate a GameObject after instantiating it.

nope cause when I want to change the rotation of every gameobject doesnt work

That code works exactly as it should. It spawns an object and resets its position to zero, and rotates it to a fixed (0,90,0) rotation.

If you want to set another rotation you need to specify it.

OP wants to first spawn 100 objects, then rotate all of them whenever he presses right or left.

The solution is very similar tho. Just keep a List to which you add whenever you instantiate your objects. Then whenever you press your key, iterate over the list and set their rotations accordingly.

yea but how to I keep a list??

Please clarify.

List<GameObject> allObjects = new List<GameObject>();

for (int i = 0; i < 100; i++) {
  GameObject go = Instantiate(prefab);
  addObject.Add(go);
}

Have the list somewhere as a member variable. Then just add the instantiated objects to it. When you want to set the rotations of your objects, do that for every object in that list with a loop.