- Home /
How to use methods with the same name from different scripts attached to this script with a reference?
How do I reference a generic script in another script? So lets say Object AO has script AS with method name "Method()". Another object BO has a script BS with the same name "Method()". Now, I want to have a script SS which will be attached to both AO and BO and have a reference to AS and BS respectively via the Unity editor. From that SS script I will do a logic which will use "Method()" name. The problem here is that I want to do in SS script:
public GameObject ao_or_bo_script;
ao_or_bo_script.Method();
but that will work only if I'll do a type cast like
(AO)ao_or_bo_script.Method();
or
(BO)ao_or_bo_script.Method();
which doens't work for me because I don't know wich script I'll attach
Answer by whydoidoit · Mar 30, 2013 at 10:42 AM
So you have three choices:
SendMessage (BroadcastMessage) which will call that method on every script attached with a matching signature
Inheritance - create a base class with a virtual Method, override it in the two A/B scripts, cast your a_or_b_script to the base class and call the method on that.
Interfaces - create an interface with the method, implement it on both scripts, cast the reference to the interface and call it with that.
Note that the GameObject isn't actually the scripts - so if you don't use SendMessage then you will have to find the components derived from the base class using GetComponent or the interface by searching through the available components.
I'll avoid Send$$anonymous$$essage() from efficiency standpoint. But thank you for the Inheritance advice!
Yep it's slow. 100x a function call - but that's usually ok for events - just not anything else! The version of GetComponent that takes a type (not the generic version with the ) can find interfaces BTW.