- Home /
Ammo crate collision
Hi. I want to make a very easy script, that adds bullets to a character when colliding with a ammo crate.
function OnCollisionEnter(crate : Collision)
{
if (crate.gameObject.tag == "Ammo")
{
print("Collision");
}
}
This script doesn't work, and I dont know why. The ammo crate have a box collider, and the Character have a Character controller and I tried to add box collider to it, but the script still didn't work. What is the problem here? Or is there a easier way to do this?
When dealing with a characterController you SHOULD use OnControllerColliderHit.
Answer by Alec-Slayden · Mar 27, 2011 at 03:10 AM
Your problem stems from the way colliders and the character controller work. The character controller is not a physical object. It's designed to react to walls and the floor as though it was, but if it really were you'd have less control over how it moves, because you'd have to obey the laws of physics in the simulation.
So its collider is more of a constant ray-cast, rather than a true collision.
Not all colliders will detect each other. Here's a chart (bottom of the page) that shows what collisions are required to detect OnCollisionEnter, and OnTriggerEnter. This can be found at the bottom of each collider page in the reference docs.
Solution 1: Your character controller will properly cause OnTriggerEnter events. You can put box collider with the "is Trigger" checked, and a script on this involving OnTriggerEnter to grant ammunition. You can have it check if the tag is player, instead of the other way around.
Since it's a trigger, it won't stop the player from moving through it, so you'll want it to be separate from the ammo crate's box collider if it's to be a solid object.
Solution 2: If you want the script to be on the player (might be a good idea if there's other stuff to grab besides ammo), you should use OnControllerColliderHit in the character controler script.
In this function you can check the hit info of the ammo crate's game object / tag, and apply the code you want.
Answer by zannghast · Oct 22, 2010 at 08:58 AM
Did you check if one of the object has a non-kinematic rigidbody attached to it?
Collider.OnCollisionEnter on the Unity Script Reference section.
I see. Forgive me for asking this, but, are you sure the object colliding with the collider is tagged as "Ammo"?
Yes. I think there is something wrong with Colliders. I made a new scene with Unitys First person controller and A box. I added my script and Rigidbody to the controller, and started the game. When colliding, nothing happened.