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.
void Awake()
{
transform.rotation.z = Random.Range(0,360);
}
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.
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));