OnTriggerStay explosion doesn't work

I wrote this code to the object disappear when it is touched by the character. Destruction + sound + explosion. Everything works as I want … except explosion. Can anyone help me understand why? Thanks

var pickupSound : AudioClip;
var explosion : GameObject;

var pickGarbage : boolean = false;

private var destroyed : boolean = false;


function Start (){
    explosion.active = false;

}

function OnTriggerStay (){

    if (Input.GetKey("c")){
        explosion.active = true;
        pickGarbage = true;
        Destroy(gameObject);

    //Play Pickup Sound
    if (pickupSound)
    AudioSource.PlayClipAtPoint(pickupSound, transform.position);
    
    print("Yes!");
    }
}

It may be that, since you are destroying the gameObject, the explosion is also destroyed.

Try changing your function to this and see if your explosion shows up:

function OnTriggerStay ()
{
    if (Input.GetKey("c"))
    {
        explosion.active = true;
        pickGarbage = true;

        //Play Pickup Sound
        if (pickupSound)
            AudioSource.PlayClipAtPoint(pickupSound, transform.position);

        print("Yes!");
        //let object live for one second before destroying
        Destroy(gameObject, 1);
    }
}

If your explosion shows up, it will show for 1 second and then destroy itself. I’m pretty sure the issue is that the gameObject holding the explosion is destroyed, and so the explosion never shows up.

Thanks Keryu, your idea is an interesting way, if the explosion is not active, it’s probably because “prefab explosion” is destroyed with the object. But I tried the code and it doesn’t work.

MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
GarbageManager.OnTriggerStay () (at Assets/Scripts/GarbageManager.js:18)

I found this code in Angry Bots. I tested it and it works. It’s easy to integrate.

var objectToSpawn : GameObject;
var onDestroyedSignals : SignalSender;

private var spawned : GameObject;

// Keep disabled from the beginning
enabled = false;

// When we get a signal, spawn the objectToSpawn and store the spawned object.
// Also enable this behaviour so the Update function will be run.
function OnTriggerEnter( otherObject: Collider) {
spawned = Spawner.Spawn (objectToSpawn, transform.position, transform.rotation);
if (onDestroyedSignals.receivers.Length > 0)
enabled = true;
Destroy(gameObject);
}

// After the object is spawned, check each frame if it’s still there.
// Once it’s not, activate the onDestroyedSignals and disable again.
function Update () {
if (spawned == null || spawned.active == false) {
onDestroyedSignals.SendSignals (this);
enabled = false;
}
}