- Home /
OnTriggerEnter() and OnCollisionEnter(), OnControllerColliderHit() not working with character controller
I have a capsule object with Camera on it. Capsule has capsule collider with mesh, character controller. cylinder object (coin) is box collider with is trigger option being on. OnTriggerObject method doesn't help to destoy the coin object. Even used OnCollisionEnter, eventually have the same result. Also tried with rigidbody added to the player object and removed from coin object. Even don't remember what I tried on.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
void Start()
{
controller = GetComponent<CharacterController>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
// Update is called once per frame
void Update()
{
UpdateMouseLook();
UpdateMovement();
}
private void OnControllerColliderHit(ControllerColliderHit other)
{
if(other.gameObject.tag == "coins")
{
Destroy(other.gameObject);
}
}
}
Answer by LilianeCastro · Jun 08, 2021 at 06:20 PM
@JuliaOlkhovyk Did you tag the coin? And wrote the right way? Sometimes I forget to tag or I write with a capital initial.
Answer by toddhdavis · Jun 08, 2021 at 06:54 PM
OnControllerColliderHit() is typically used when you want to keep hitting something with the controller, such as pushing an object around. To hit a coin and make it disappear, perhaps OnCollisionEnter() would be a better choice. Also, just as a personal suggestion, I try (when I can) to make objects responsible for themselves. So in other words, other than having the player controller managing coins, have a CoinController that will acknowledge when it's been collided with, and destroy itself. Separation of concerns and all. :)
I would suggest:
Edit your collider and just make sure that it encompasses the capsule. In other words, make sure it is not too small or offset, etc.
Put a rigidbody and collider on the capsule
Put a collider on the coin, make it a trigger, and respond to it in the coin script
To the best of my knowledge, there must be at least one Rigidbody in a collision, and two triggers cannot trigger each other, so just bear those things in mind.