- Home /
How to instantiate a prefab after its been destroyed
So heres what im trying to do. I want to have a prefab instantiated on a collision, appear for two seconds, then be destoyed. This will get called repeated times. After the first time, i get the error that the gameObject trying to be instantiated has already been Destroyed. I tried making a temporary gameobject to be instantiated and destroyed, but the call to destroy is in a different method (and needs to be since their being called from a seperate script) so i cant reference that temporary gameObject. I know i figured this out before and can be done, but i forget how i did it. heres my code using UnityEngine; using System.Collections;
public class changeCursor : MonoBehaviour {
double t;
float tf;
public GameObject cursorAnimation;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void wait(float x){
t = Time.time;
tf = Time.time + x;
while(t < tf){
t = t + 0.001;
}
}
public void playAnimation(){
GameObject cursorInstance;
cursorInstance = (GameObject) Instantiate (cursorAnimation, transform.position, transform.rotation) as GameObject;
}
public void hideCursor(){
gameObject.GetComponent<Renderer> ().enabled = false;
}
public void goBackNormal(){
Destroy (cursorInstance);
gameObject.GetComponent<Renderer> ().enabled = true;
}
}
Answer by Alec-Slayden · Jul 26, 2015 at 01:14 AM
The code you posted shouldn't compile, and you shouldn't even get to play mode: cursorInstance is only defined in the scope of playAnimation(), but you are using it in goBackNormal(). I assume this is code that was intended to fix your problem but didn't work yet. Close though! you're only one step away :)
define cursorInstance as a private variable at the top of your script, and remove its declaration from playAnimation(). That way you can use it in other methods, including where it needs to be destroyed.
EDIT: As a side note, your wait method isn't a coroutine, and so probably won't do what you expect. As it stands now, it will set “t” equal to “tf” in one frame, because the while loop will keep working until it’s finished. Using a coroutine you can yield until the next frame. I am not sure what you are trying to do with it, or i would provide some examples, but I recommend looking into coroutines.
this was the second code, it doesnt compile. the first one did but would give me that error. This is working. The problem im having now is the Destroy call is just not working now for some weird reason
I'd have to see the code that calls the methods to help with that unfortunately.