- Home /
OnTriggerEnter - if other is of type, invoke method
I want to see if the object we are colliding with is of a certain type and then invoke a member function specific to that type's class.
I can easily check to see if the other object is the type I want with a simple name or tag comparison, but then the method I want to call obviously can't be called because Collider doesn't contain a definition for it.
Example code of issue, where Disable is a method in the Block class:
void OnTriggerEnter (Collider other)
{
if(other.tag == "Block")
{
other.Disable();
}
}
What's the best way get around this?
Answer by smoggach · Oct 21, 2014 at 06:25 PM
All monobehaviours have properties linking to their GameObject. so if you wanted to disable other, you could do
other.gameObject.SetActive(false);
You can also just do
other.GetComponent<WhateverScriptYouAreLookingFor>().SomeFunctionYouWantToRun();
I should have used a better example than Disable as I'm not trying to completely disable the object, but your second option is obviously fine, thanks.
Answer by Kiwasi · Oct 21, 2014 at 06:32 PM
Better to do a null check first.
MyScript myScript = other.GetComponent<MyScript>();
if(MyScript){
// Do something awesome
}
Note: You are also abusing the word type. The type of every GameObject is GameObject. What you are asking to do is check if the GameObject has a specific component attached.
Your answer
Follow this Question
Related Questions
How to make gameObject make only one collision 1 Answer
How to have a score counter increment in OnTriggerEnter 1 Answer
onEnterCollider returns Collider 1 Answer
Distribute terrain in zones 3 Answers
How Does OnTriggerEnter() Work? 0 Answers