Hello, i have been doing a game where i want to instantiate a particle effect when i press ‘K’ and after 3 seconds destroy it. But i want to do it each time i press ‘K’. With this code i get an error saying: Missing Reference Exception, the object has been destroyed but you are still trying to access it. so if anyone could give me some sort of advice how to fix this problem.
This is the code i have been using.
public GameObject probaParticle;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (probaParticle != null)
{
if (Input.GetKeyDown (KeyCode.K))
{
probaParticle = Instantiate (probaParticle, transform.position, Quaternion.identity) as GameObject;
Destroy (probaParticle, 3);
}
}
}
When you Instantiate, you don’t assign the instantiated clone of probaParticle to a new GameObject variable, but rather assign it to the prefab you just used to instantiate a clone of. That means that if you destroy probaParticle the variable becomes null and you can’t instantiate a clone of it again.
The solution of course is to just declare a new (temporary) variable for the clones.
if (Input.GetKeyDown (KeyCode.K))
{
GameObject probaParticleClone = Instantiate (probaParticle, transform.position, Quaternion.identity) as GameObject;
Destroy (probaParticleClone , 3);
}
public GameObject probaParticle;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (probaParticle != null)
{
if (Input.GetKeyDown (KeyCode.K))
{
GameObject gObject = Instantiate (probaParticle, transform.position, Quaternion.identity) as GameObject;
Destroy (gObject, 3);
}
}
}