- Home /
OnCollisionEnter multiple objects
Hi, first post here.
I'm having a problem getting OnCollisionEnter to work with another object. Basically in my game I have coins that fall down from the sky. The player is supposed to collide with the coins and the coins should disappear (basic mario stuff). Now these coins have a rigidBody on them because I want to use gravity to make them fall. The issue I run into is once the Coin has reach the ground it enters collision with the ground and The player cannot pick it up. However if the player reaches the coin before it touches the ground it works properly and disappears. I'm not sure what's going on with OnCollisionEnter and why the player can't just pick up the coin when it's on the ground.
Here's my code for the Coin...
function Start ()
{
Physics.gravity = Vector3(0,gravityValue,0);
}
function OnCollisionEnter(other:Collision)
{
print("COLLiDING");
if(other.gameObject.tag == "Player")
{
print("touching coin");
Destroy(gameObject);
}
}
well I decided to AddForce of 0 to the coin once it's velocity reaches 0. This wakes up the coin so the collisions still work.
Answer by sparkzbarca · May 21, 2013 at 10:08 PM
because when rigidbodies stop moving they go to sleep to improve performance.
http://docs.unity3d.com/Documentation/Components/RigidbodySleeping.html
kinematic rigidbodies will wake up sleeping ones.
but there are other solutions
you can easily simulate gravity
during update simply move down if they aren't grounded.
if you want to use rigidbodies do a line where you go
if (mathf.approximately(rigidbody.velocity, vector3.zero) //so if your not basically stopped
{
//remove the rigidbody component
}
now it doesn't have a rigidbody and the gravity is over you don't need it now you can collide.
Answer by aamesxdavid · May 21, 2013 at 10:17 PM
Basically, what sparkzbarca said, but personally, I've had more luck with keeping all of that code on the player end. That is, have an OnCollisionEnter() function in your player object, and tag the coins. Then, send a message to the coin to destroy it, and add your score/points wherever. So for your player:
function OnCollisionEnter(other:Collision)
{
if(other.gameObject.tag == "Coin")
{
print("touching coin");
other.SendMessage("PickUpCoin");
myScore += 1;
}
}
And then in your coin object:
function PickUpCoin()
{
Destroy(gameObject);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613102704im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
HELP Find gameObject With tag in another array 1 Answer
How to tell if 2 blocks are next to each other in a 2d game? 1 Answer
GameObject block particles?! help 4 Answers
I made a better shader how do i fix[add _Shadow Strength]help???>Sorry that im asking for to much 1 Answer