- Home /
Collider script refuses to work
I am making an Android game, and when the player touches a coin, it adds it to the score and destroys the coin object. But the code refuses to work, and I don't know why. The coin has a mesh collider on it, and I thought maybe that was the issue. So I tweaked the code to detect rocks instead, which have sphere colliders on. Still no luck.
var PlayerCoins : int;
var CoinText = "Coins: " + PlayerCoins;
function OnTriggerEnter(other : Collider)
{
if(other.tag == "coin")
{
PlayerCoins +=1;
CoinText = "Coins: " + PlayerCoins;
Destroy(other.gameObject);
}
}
Answer by hamstar · Mar 30, 2014 at 10:28 AM
Hard to know exactly, but here's a guess.
You might need to use OnCollisionEnter...
I imagine that your Player object is not using a trigger collider, but perhaps your coin object is. Therefore, since this script is attached to the player, you should use `OnCollisionEnter`. You would use `OnTriggerEnter` if the script was attached to an object with a trigger collider.
If you are working with 2D colliders...
You should use `OnTriggerEnter2D` or `OnCollisionEnter2D`.
Make sure your coin game object definitely has the tag "coin".
I've tried both, and it's still not working. I made sure I followed what I was supposed to do in the documentation.
You could try this test code to check if any collisions are registering:
function OnTriggerEnter(other : Collider)
{
Debug.Log("OnTriggerEnter - Collided with object tag: " + other.gameObject.tag);
}
function OnCollisionEnter(collision : Collision)
{
Debug.Log("OnCollisionEnter - Collided with object tag: " + collision.gameObject.tag);
}
What is the output?
I'm a bit stumped then sorry. Can you try this, just to make sure?
function Start () {
Debug.Log("I am attached to a game object!");
Debug.Log("$$anonymous$$y game object is, name: " + gameObject.name + " tag: " + gameObject.tag);
Debug.Log("I have a 3D collider?: " + (collider != null));
Debug.Log("I have a 2D collider?: " + (collider2D != null));
}
Does the object with the script have a rigidbody? From docs:
Note that collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.
Your answer
![](https://koobas.hobune.stream/wayback/20220613141529im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can to convert it on c#? 1 Answer
Collide script not working... 1 Answer
Footstep Audio Check Collider Hitting Floor 1 Answer
Adding varibales from other scripts 3 Answers