- Home /
How can i add random range to an instantiated objects rotation?
To get a better understanding, imagine a jigsaw puzzle with all its little pieces, i currently have any empty spots being replaced with new pieces, but they always spawn with a default rotation of 0, 0, 180 and I want that 180 to be random choice between 0, 90, 180, 270.
Instantiate(objs[(Random.Range(0, objs.Length))], Vector3(x,y,z), Quaternion.Euler(0, 0, (rots[(Random.Range(0, rots.Length))])));
Before Quarternion.Euler i was using Quarternion.identity with nothing else after it to the the standard rotation. I don't understand how this doesn't work. I get the error -
IndexOutOfRangeException: Array index is out of range. !CompareApproximately (det, 1.0F, .005f) UnityEngine.Quaternion:LookRotation(Vector3, Vector3)
Note that the first half of that line works fine its just the rotation bit after Quarternion.Euler that started these errors
Your error IndexOutOfRangeException may be fired from that line, but that line of code itself is sound. Would you be able to provide the rest of the code where you are assigning values to rots[]?
Answer by Cherno · Mar 19, 2014 at 02:11 AM
Kinda clumsy, but why not add something like this after instantiating with Quaternion.identity? helps keep the lines short)
var randomNumber : int = Random.Range(0, 4);//the 4 is exclusive for int Randon.Range
instantiatedObject.transform.rotation = Quaternion.Euler(0, 0, randomNumber * 90);//gives 0, 90, 180, or 270
Whilst that does work, despite this error i get - ArgumentException: RandomRangeInt can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene.
Still don't understand why $$anonymous$$e doesn't work :( In regards to that error though, you know what's the deal with that.
Based on the error, are you attempting to execute your code outside of a function like Start() or Awake()? If so, move this code to Awake() or Start().
Solved the error... just moved the randomnumber variable inside the instantiate function. Now if any one can tell me why $$anonymous$$e doesnt work that would be great
Your answer
Follow this Question
Related Questions
Random Rotation With Limited Range? 2 Answers
Random rotation 2 Answers
transform.eulerAngles Problem 2 Answers
Random object, Array index out of range 0 Answers
Camera Script Rolling on the Z 3 Answers