I have a script that instantiates one rigidbody a frame. then the rigidbodys delete themselves after one second. when the rigidbodys get deleted the game lags heaps. How do you get only 10 rigidbodys to be created in a second and is there any way to delete a rigidbody without lag?
I would think that instantiating something every frame would be causing the lag, not the destruction of the objects. If you're spawning faster than you're destroying, eventually you're going to reach the limit of your CPU/memory (seconds 0-1 have 60 objects, seconds 1-2 have 119 objects, seconds 2-3 have 178 objects, etc). This is assuming you're instantiating a prefab with a rigidbody component attached to it, then using the Timed Object Destructor script provided with Unity to destroy the rigidbodies after they've been around for 1 second. This should spawn one prefab every 1/10th of a second:
var spawnInterval : float = 0.1;
private var lastSpawn : float;
var myRigidbody : GameObject;
function Update() {
if (Time.time > lastSpawn + spawnInterval) {
Spawn();
}
}
function Spawn() {
lastSpawn = Time.time;
Instantiate (myRigidbody, transform.position, transform.rotation);
}
If you're wanting to "clear the slate" every second and delete them all at once (rather than give them each a 1 second lifespan), you'd need to do something different. Maybe add each game object to an array every time you create one, and then using a similar timer as the spawning timer above, delete every rigidbody in the array each second. So something like:
var deleteInterval : float = 1.0;
private var lastDelete : float;
var spawnInterval : float = 0.1;
private var lastSpawn : float;
var myRigidbody : GameObject;
private var arr : Array = new Array();
function Update() {
if (Time.time > lastDelete + deleteInterval ) {
Delete();
}
if (Time.time > lastSpawn + spawnInterval) {
Spawn();
}
function Delete() {
lastDelete = Time.time;
for (i=0;i<arr.length;i++) {
Destroy(arr*);*
*}*
*function Spawn() {*
*lastSpawn = Time.time;*
*var newRigidbody : GameObject = Instantiate (myRigidbody, transform.position, transform.rotation);*
*arr.Add(newRigidbody);*
*}*
*```*
*<p>Though I think the feature as implemented this last way would be more laggy, since it's looping through each game object and destroying them all in the same frame/game cycle.</p>*
If you are creating 1 every frame and deleting 1 every second, then your game will more than likely crash.... eventually. Even if you limit the rigidbodies to 10:
1 second = 10 objects
2 second = 19 objects
3 second = 28 objects
you might want to manage this a different way.