- Home /
 
Destroying an instance problem
I am trying to destroy the clone instance as in the code below:
 var projectile : Rigidbody;
 var creationtime:float;
 var timerfl:boolean=false;
 function Update () {
    var curtime:float;
    if (Input.GetButtonDown("Fire1")) {
       var clone : Rigidbody;
       clone = Instantiate(projectile, transform.position, transform.rotation);
       clone.velocity = transform.TransformDirection (Vector3.forward * .5);
       creationtime=Time.realtimeSinceStartup;
       timerfl=true;
    }
    curtime=Time.realtimeSinceStartup;
    if(timerfl==true){
        if((curtime-creationtime)>5)
        {
           timerfl=false;
           Destroy(clone);
        }
     }
 }
 
               but the clone is not destroyed, what am I doing wrong? Thanks
               Comment
              
 
               
              Please hit 'edit', then select your code, then hit the '010/101' button to format your code.
Answer by syclamoth · Nov 04, 2011 at 01:40 AM
The problem is that 'clone' only exists within the scope of the if statement in which it is created! You need to define 'clone' outside of that scope, i.e, at the top of your script with the member variables.
So, add the line
 private var clone : Rigidbody;
 
               at the top, and delete that line from before it gets instantiated. That way, you will keep a reference to your instantiated object outside the scope in which it was created.
Your answer