- Home /
How to cast/convert a ControllerColliderHit into a Prefab
Hi guys.
I have the next code:
void OnControllerColliderHit (ControllerColliderHit hit) {
if (hit.transform.tag == "Coin") {
Coin coinDestroyed = (Coin)hit.gameObject;
coinDestroyed.CoinCatched ();
Destroy (hit.gameObject);
GameManager.Instance.CoinCollected ();
}
}
I am trying to cast the "Coin" Object that has been hit in order to call one of its methods (CoinCatched). But I have not found the way to cast the object. Any help will be great.
Answer by tonOnWu · Aug 01, 2017 at 05:40 PM
After researching a lot I found the best solution for my request: I used OnTriggerEnter inside the Script Component of my Object "Coin", like this:
void OnTriggerEnter(Collider other) {
if(other.transform.tag == "Player") {
Destroy (gameObject);
GameManager.Instance.CoinCollected ();
}
}
Last step, I set "Is Trigger" onto the Sphere Collider Component of the Coin object. This gave a better control of every object independently. Perfect.
Answer by Ataraxxis · Jul 31, 2017 at 01:17 PM
Assume "Coin" is a script, use hit.gameObject.GetComponent<Coin>();
instead.
Your answer
![](https://koobas.hobune.stream/wayback/20220612131606im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
casting string as type(for passing to method calling for type)? 1 Answer
C# - Resources.Load Sprite trouble 2 Answers
I'm having .ToString Problems 1 Answer
Is There A Way To Cast On 1 Returning Value 2 Times? 5 Answers
Casting Object to Rigidbody 2 Answers