Search code examples
c#unity-game-enginegame-physics

I have wrote a script for a destructible object, however it doesn't break the destroyed object after a certain time?


public GameObject BrokenBottle;
AudioSource audioSource;

void Start()
{
    audioSource = GetComponent<AudioSource>();
}

private void OnCollisionEnter(Collision collision)
{
 if(collision.relativeVelocity.magnitude > 2)
    {
        
        Instantiate(BrokenBottle,transform.position, transform.rotation);
        Destroy(this.gameObject);
        Destroy(BrokenBottle,1.5f);
        audioSource.Play();
    
    }

}

}

I have created a script for when i smash a bottle it destroys the non smashed bottle and then instantiates the destroyed bottle. However i'm trying to destroy then broken bottle (with the GameObject BrokenBottle) after 1.5f, but instead the broken bottle still stays.


Solution

  • You're destroying the wrong object.

    Instantiate takes the original object as a parameter and then returns a copy. You should assign returned object to local variable and pass it to the destroy call:

    var brokenBottleInstance = Instantiate(BrokenBottle,transform.position, transform.rotation);
    Destroy(brokenBottleInstance, 1.5f);