I was wondering how to write a script to accomplish this goal. I have about twenty objects in my scene and I want a object (with the script applied to it) to randomly add rigidbodies to these objects, and randomly within a specified time range. For example the object would add a rigidbody some random time within 0-3 seconds to one of the specified objects. Not sure how to do this. I’m sure I could get there eventually, but the script would probably be unnecessarily long and with less control. Thanks for any help!
That kind of script wouldnt be hard. It depends if these are runtime object or not. Either way, you would start with a list of objects. then simply add the rigidbody statement.
// use an array for some neat functions..
var objects : Array=new Array();
// at this point, the user could load the object array or you could do it via code.
for(var i =0; i< 20; i++){
objects.add(GameObject.CreatePrimitive(PrimitiveType.Cube).transform);
var newPosition : Vector2 = Random.insideUnitCircle * 25;
objects[i].position.x = newPosition.x;
objects[i].position.z = newPosition.y;
}
//Random Drop...
var n : int = Random.value * objects.length;
objects[n].gameObject.AddComponent(Rigidbody); // make it fall
objects.RemoveAt(n); // remove it from the list so we dont have it to drop again.
}
I don’t think this is what I meant. Imagine twenty tiles in the scene. We’ll just say that on function Start() the tiles start to fall one by one over the time of about three seconds (kinda like a disintegrating effect). The tiles are already in the scene so I don’t need to add any other objects. See the images below:
erm… I think what i had was rathr open ended to that. You can either fill the array yourself, or let Unity do it in the Start() function…
Speaking of the Start() function. it is a function that only happens at the beginning. You will need to add some code to make things drop randomly during the Update function.
coupled with my previous entry…
var timeToNextDrop = 3.0; // start after 3 seconds..
function Update(){
if(Time.time < timeToNextDrop) return; // if we are not ready to drop one, just quit
// using the array from the previous post...
//Random Drop...
var n : int = Random.value * objects.length;
objects[n].gameObject.AddComponent(Rigidbody); // make it fall
objects.RemoveAt(n); // remove it from the list so we dont have it to drop again.
// update timeToNextDrop to add 2-3 seconds onto the timer
timeToNextDrop = Time.time + Random.Range(2.0, 3.0);
}