- Home /
How can I delete my instantiated prefab coin upon collision?
Hey guys, I have a fairly simple game I'm making. You control a barrel and collect coins that fall at random speeds. In Unity, I have a Cube with a Box Collider set to it. This cube is set inside the barrel so that when you collect a coin , the coin enters the barrel and is deleted on impact with the cube. I also have a coin prefab that is instantiated every 2 seconds and has a sphere collider and rigidbody set to it. These fall and the player has to try to collect them in the barrel. However, when I attach my script to the cube, the coin is not deleted upon collision. Matter of fact , the coins actually stack on each other and then get deleted. All I want is for the coins to enter the barrel , hit the cube collider and then get deleted. I'm not sure why this is happening. Help!
[the code attached to the coin.]
using UnityEngine;
using System.Collections;
public class CoinEntererScript : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter(Collision Silvercol)
{
if(Silvercol.gameObject.tag == "SilverCoin")
{
Destroy(gameObject);
}
}
}
Answer by tomowale · Sep 05, 2016 at 09:30 AM
I figured it out. For those reading this and may have been having the same issue. Make sure the object your trying to delete on collision has a collider and a rigidbody . Also make sure the collider object has a rigidbody and a collider with the is trigger checked. Here is my code.
using UnityEngine;
using System.Collections;
public class CoinEntererScript : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider Silvercol)
{
if (Silvercol.gameObject.tag == "SilverCoin")
{
Destroy(Silvercol.gameObject);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612092141im_/https://answers.unity.com/themes/thub/images/avi.jpg)