I am trying to make it so when my spaceship game object collides with a coin game object the coin gets destroyed, I have this script attached to the coin and nothing happens when it collides.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectCoin : MonoBehaviour {
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
Destroy(this.gameObject);
}
}
}
I also have attached a circle collider with is trigger checked as well as a rigid body 2d, I have those on the spaceship as well minus the on trigger.
Firstly, check to see if that function is actually getting hit using a Debug.Log statement or something. If not, then check that one or both objects colliding have a Rigidbody and that they both have Colliders, with the Coin’s collider being set to Trigger. Also check that both objects are on a layer that can collide according to the collision matrix in Edit>ProjectSettings>Physics2D.
If your Player has a unique component on it, such as a “PlayerController” or something of the sort, a better practice is to check if the incoming object has a component, rather than a tag.
public class CollectCoin : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
Player player = other.GetComponent<Player>()
if (player != null)
{
Destroy(gameObject);
}
}
}
Reason being, tags change, and you don’t want to have to update strings in your code which are also subject to typos. Plus you can only have one tag per object, whereas with components you can have many components to check for, and you can check the data that a component holds to further identify an object without needing raw strings.