- Home /
Random z rotation instantiate
I am trying to spawn an object in my scene but I want it to have a random z rotation when it is created. I thought about simply applying a script to it...like so.
[code]
void Awake() { transform.rotation.z = Random.Range(0,360); } [/code]
I think the cleaner and best way would be to instantiate it with a random rotation in the z axis. I know Quaternion.Random will produce a random rotation in all axis, but is there a way to simple do it to the z axis only?
I am not familiar with quaternions so any explanations would be appreciated. Currently trying to figure them out instead of avoiding them.
I admire your desire to understand and work with Quaternions, but having tried myself to wade through this explanation of how they work, I decided to stick with Euler angles... in fact, the Unity documentation itself recommends that "you almost never access or modify individual Quaternion components".
I personally don't see anything particularly unclean about your current approach :)
How should I go about instantiating my object so that it has a random orientation in the z axis? Is there a way to do that with euler angles?
Answer by robertbu · Oct 29, 2013 at 09:41 PM
A transform.rotation is a Quaternion. The x,y,z,w values range from 0.0 to 1.0 and are not intuitive. There are a number of ways to get what you want here. In part the solution will depend on whether you have any unknown x and/or y rotation.
For applying a random rotation on the 'z' to an unknown rotation:
void Awake() {
transform.Rotate(0.0, 0.0, Random.Range(0.0, 360.0));
}
This is a relative, rotation around the local 'Z' axis.
If you don't have any rotation on the x or y, or if you know the rotation, then you can put it directly in the Instantiate():
Instantiate(somePrefab, somePosition, Quaternion.Euler(0.0, 0.0, Random.Range(0.0, 360.0));
Excellent answer, thank you. So let me see if I have this right...Quaternions range from 0,1 and by doing Quaternion.Euler you are able to hand it 0-360 and it does the conversions for me?
Yes. As @tanoshimi says, the reference manual recommends against manipulating Quaternion components directly. There are a variety of helper functions that can be used in a large number of ways to solve rotation problem. For example, here are alternate solutions:
Instantiate(somePrefab, somePosition, Quaternion.AngleAxis(Random.Range(0.0,360.0), Vector3.up));
And here is one for a relative rotation:
transform.rotation = Quaternion.AngleAxis(Random.Range(0.0,360.0), transform.up)) * transform.rotation;
Your answer

Follow this Question
Related Questions
Help platform rotating on x-Axis passes through colliders 0 Answers
My tank will flips on the air when it collide other objects. 1 Answer
Issue moving Object around surface of sphere 3 Answers
Animated objects rotation is flawed. 1 Answer
How do I rotate an object over time outside the Update method? 2 Answers