- Home /
How to check if a certain method is implemented
Hi! I'm making a classical point&click quest and need to know if some object can be pushed/used/etc. Main camera object script raycasts such objects and stores a reference to them. Player object script has main camera as a public variable and asks it for that reference. And at this point I don't know how should I proceed further. First, it seems like I cannot use a reference to a reference like this cameraScript.clickedObject.someMethod(). It logs an error for some reason. Second, if I use cameraScript.clickedObject.SendMessage("someMethod") I need to know right away if that method is implemented. I thought maybe SendMessage returns true/false for success/failure or some error object can be used but found none in the documentation. Thanks!
Answer by Kiwasi · Oct 15, 2014 at 06:15 PM
You can use reflection to discover if a method exists.
What is reflection? Is it unity or boo feature? A link would be great
Reflection is a .NET feature. Here is the link to the documentation. It works in C#, not sure where you would go for documentation in JavaScript. You really don't want to touch Boo, the language only exists for historical reasons.
Be warned this is some pretty heavy coding. If the GetComponent solution works as suggested by @Julianobsg then use it. OOP constructs like interfaces and inheritance often can be used as well. But if you must be able to detect if a method is implemented on a object without knowing details of the object in advance then reflection is the way to go.
Answer by Mel Zombie · Oct 17, 2014 at 01:22 PM
Here is how I've done it:
if cameraScript.clickedObjectScript != null and cameraScript.clickedObjectScript.GetType().GetMethod("method"): cameraScript.clickedObjectScript.SendMessage("method")
A script per command also works fine if overly complicated in my case. Thanks to everyone!
Answer by Julianobsg · Oct 15, 2014 at 06:51 PM
Use a
if(gameObject.GetComponent<Pushable>() != null)
and will return true or false if there is any component of that class there.
You don't need to use a single class for everything, you can create a class and add that property to any go, and is cleaner sometimes. You can also check a tag, if you put a tag pushable in the go for example.
Just to be clear, if you use GetComponent, you should really not have to use Send$$anonymous$$essage as well. You should be able to something like the following:
// wherever your camera / clicked object stuff is
var clicked = camera.ClickedObject.GetComponent<SomeType>();
if(clicked != null)
{
clicked.Some$$anonymous$$ethod();
}