- Home /
Generic Component Declaration
I have a script I'm accessing via GetComponent as such:
Script myscript = GetComponent<Script>();
But I also have variants such as:
Script2 myscript = GetComponent<Script2>();
What I'm looking for is a generic way of declaring a method perameter so that I can have a function that receives both:
void myfunc(Script scriptToAcess)
{
//Do things with the either script
}
My problem is the way declaration works, my method can only accept Script or Script2. Is there a generic way to type these components so my method can accept either?
Thanks!
Answer by ScroodgeM · Aug 21, 2012 at 08:56 PM
create myfunc that takes Component type or MonoBehaviour type. this will let you pass any script to input
or, make all Script and Script2 and either as child of some abstract type, also create myfunc accepts this abstract - so you also be able to pass any chilf of abstract type to input
I get this error when I use Component or $$anonymous$$onoBehaviour ins$$anonymous$$d of the actual script name.
Type `UnityEngine.$$anonymous$$onoBehaviour' does not contain a definition for `script$$anonymous$$ethod' and no extension method `script$$anonymous$$ethod' of type `UnityEngine.$$anonymous$$onoBehaviour' could be found (are you missing a using directive or an assembly reference?)
this caused by you trying to execute method on $$anonymous$$onoBehaviour without casting it to your type. do following:
if (scriptToAcess is Script2) { Script2 s2 = scriptToAcess as Script2; s2.script$$anonymous$$ethod(); }
But doesn't that defeat the purpose of a generic method that handles all of these different scripts if I'm having to manually cast each one?
I'd have to write another if statement with that code for Script3 and Script4 etc...
Second solution worked great. Created class Script.
classes Script1 and Script2 extend Script
$$anonymous$$ethod takes Script as an argument and allows Script1 and Script2 to be passed without errors. Thanks again!
Your answer
Follow this Question
Related Questions
get component type at runtime using generic GetComponent in C# 1 Answer
C# Generic return type 1 Answer
Multiple Cars not working 1 Answer
Referencing a c# component script from JS script 2 Answers
Distribute terrain in zones 3 Answers