- Home /
Instantiate from flexible array
I have a java array () type.
I generate a random number and get an object from that array,
i then declare an object from the array at position (i)
i then removeat (i) in the array for i do not want to initiate the same object twice.
i then instantiate the object.
here is the problem. sometimes the object is declared before the previous one is distorted and i get an object that is not in the array any longer. is there any way to wait for the remove at to finish before i generate the now (i)? Here is my code
var i = Random.Range(0,listWhites.length); var theObject : GameObject = listWhites[i]; listWhites.RemoveAt(i);
var numbers = GameObject.Find("compair");
if (spawned) return; spawned = true;
var newobject = Instantiate (theObject) as GameObject;;
First question, where is "spawned" declared? Is it a local variable or class variable?
Second, what function is containing the code you showed us? The update function? Start function? or is it a function that is called after some event happens? If so, what event.
Third, I don't think I understand "sometimes the object is declared before the previous one is distorted". Did you mean "sometimes the new object is instantiated before it is removed from the array"?
Not sure I know the answer, but I'm sure that the "RemoveAt" function happens immediately, the next line of code cannot execute until it is done. I'm guessing here that the real problem is in some other part of your code. I would take a close look at how that "listWhites" array is created and updated elsewhere.
Have you checked in debug mode that the array indeed does not have any duplicate entries in it to begin with?
http://unity3d.com/support/documentation/$$anonymous$$anual/Debugger.html
How about using an array shuffling method, and then just instantiating the whole thing in order? Sounds much more straightforward than what you're doing here.
Your answer
![](https://koobas.hobune.stream/wayback/20220612225446im_/https://answers.unity.com/themes/thub/images/avi.jpg)