Destroy issue

There seemed to be a lot of questions about this but I could still not solve my problem from the answers. My test is simple, I have a shot that leaves the canon and I want it to self destruct when a counter reaches 60 by calling the Destroy() function.

var projectile : Rigidbody;
var speed : int;
var counter : int = 0;
var round : Rigidbody;

function Update () {
	if (Input.GetButtonUp("ballFire")){
        round = Instantiate(projectile, transform.position, transform.rotation);
 		round.velocity = transform.TransformDirection (Vector3.forward * 100);
	}
	
	if(counter == 60){
		Destroy(round);
	}
	counter++;
}

I am sure I am missing some small step here?

That won’t work right because Update runs once per frame, not at any set interval, so the time it takes counter to equal 60 will vary. Just use the time parameter of Destroy. Also you don’t need TransformDirection for this. Assuming you want to destroy the game object rather than the rigidbody component, you need to specify that.

if (Input.GetButtonUp("ballFire")) {
        round = Instantiate(projectile, transform.position, transform.rotation);
        round.velocity = transform.forward * 100;
        Destroy(round.gameObject, 1.0);
}

–Eric

I see what you are doing. I over looked that Destroy had a time parameter. Just wondering since I am learning, The Destroy line of code you say round.gameObject, 1.0. Is this the same as referring to this as ‘this’? Or is gameObject another way of saying ‘this’? If I am firing a bunch of objects called round I would think I need to refer to this one?

Thanks you.

Not quite sure what you mean…gameObject refers to the GameObject for “round”. “this” refers to the class, and you don’t usually need to use it, mostly when distinguishing between global and local parameters. e.g.,

class Foo {
    var x : int;
    function Foo (x : int) {
        this.x = x;  // Make global "x" equal local "x"
    }
}

Can you rephrase? I don’t know what “this one” is referring to.

–Eric

im a little confused with eric’s opinion, but why not add the

yield WaitForSeconds(60)
Destroy(gameObject)

If this class is extending MonoBehaviour then destroying ‘this’ will destroy the instance, or object who’s timer has expired, not every object in the scene that use the same script.

The ‘gameObject’ allows you to access another object, be it with the same or a completely different script component.

Because it would add quite a lot of complexity to make that into a coroutine. There’s no reason to do that, just use the time parameter in Destroy like I did in my code.

–Eric