- Home /
Calling methods on other Game Objects
Hello! This might be an easy problem. Maybe.
Say I have an Arrow, and on collision with an object I want it to call a method "Hit" contained on a script component of the target.
So from the arrow's script:
void OnCollisionEnter(Collision col)
{
var com = col.gameObject.GetComponent<ArrowReceiver>();
com.Hit();
}
That's all fine but, what if there are two targets cases to consider? Say a "Blue" target which has script component "BlueReceiver" and a "Red" target which has script component "RedReceiver". Both unique scripts of both unique targets have the method Hit.
So I still want to call the method Hit, but I don't know which case I've collided with and therefore don't know which component (BlueReceiver or RedReceiver) to access.
I've tried parsing the name.ToString() of the Game Object I hit with + "Receiver" to get a string called "XReceiver" where X is the name of the Game Object I hit, but I can't use GetCompnent with a string.
Any thoughts?
Answer by robertbu · May 31, 2013 at 02:24 AM
In C# there are several different ways of dealing with this situation. See the answer by @asafsitner here and his references to 'Interfaces', 'Abstract Classes', and 'Overrides'. Typically I solve this problem by creating an 'ArrowReceiver' base class and derive my 'RedReceiver' and 'BlueReceiver' classes from the base class. The base class would have a Hit() method, so the collider code can deal with either.
You can also use the brute force approach. First try and get and use the 'RedReceiver' component. If it comes back null, then try to get and use the BlueReceiver component.