- Home /
Ball wont destroy in collision even though that the ball are public GameObject
Sorry I am Bad in English. I have 6 color bar and ball The ball doesn't destroy when collide it go through the color BAR
public GameObject Ball;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject == Ball)
{
Destroy(col.gameObject);
}
}
][1]
Answer by twrabetz · Mar 31, 2020 at 09:05 PM
Hello,
If you instantiate a prefab, Unity will create "clones" of it, which might not actually register as the same GameObject. You should do as Curve's answer suggested:
1- Go to your Ball prefab and in Tags at the top of the inspector, click the dropdown and select the "Add Tag.." option. Add a new PurpleBall tag and then select that new tag from the dropdown.
2- In your code, check if (col.gameObject.CompareTag("PurpleBall")) Destroy(col.gameObject).
If I might add this here: http://blog.13pixels.de/2019/why-strings-are-not-your-friend/
Answer by Codester95 · Mar 31, 2020 at 08:59 PM
Give this a try :)
public GameObject Ball;
void OnTriggerEnter2D(Collider2D col)
{
if(col.tag == "TargetTag"){
Destroy(col.gameObject);
}
}
Answer by FlaSh-G · Mar 31, 2020 at 09:24 PM
The ball you collide with is not the same object as the prefab, so your comparison evaluates to false. There is also no way that you can ask Unity "which prefab is this object an instance of?".
What you have to do is: Make a new script that contains some means of identification. I'll use an enum as an example, but there are many ways to do this - which is better is depending on your situation.
public class BallType : MonoBehaviour
{
public enum BallColor
{
Blue, Gold, Green, Purple, Red, White
}
// public field for simplicity
public BallColor color;
}
You put this on each of your ball prefabs and set the right color on each.
Your collision script then also has a BallColor property and checks against that in OnCollisionEnter:
public BallType.BallColor collidingColor;
private void OnCollisionEnter(Collision collision)
{
var ballType = collision.gameObject.GetComponent<BallType>();
if (ballType && ballType.color == collidingColor)
{
Destroy(collision.gameObject);
}
}