c# - Call a function on AddComponent( string variable ) -
type thistype = stringvar.gettype(); thistype myscript = gameobject.addcomponent(stringvar); myscript.runcustomfunction();
this doesn't work, , believe because cannot cast variable type if don't know variable type @ compile time (rather run), therefore unable directly access component added.
i have gameitem class pulls default values script, puts them dictionary. based on dictionary entry "functionscript","myscript", need attach myscript object, pass dictionary entries.
alternatively, inefficient , ask item class variables on myscript class, i'd rather avoid.
system.type
actual type, same system.int32
, or system.guid
. can't use variable static identifier in code since compiler has no idea type is.
i think trying construct concrete type based on name.
you can use activator.createinstance this, long know type name , assembly name.
var typename = "mytype"; var mytype = activator.createinstance("myassembly", typename);
you use dynamic
keyword let dlr handle heavy lifting you.
dynamic mytype = activator.createinstance("myassembly", typename); mytype.runcustomfunction();
if type inherits common base type, or implements interface, can cast type , call method.
//safe cast base type var mytype = activator.createinstance("myassembly", typename) basetype; //or safe cast interface var mytype = activator.createinstance("myassembly", typename) imytype;
however, if types not inherit known type, know have method called runcustomfunction
, don't want use dynamic
can use little reflection invoke method.
//create system.type using assembly qualified name var typename = "mytype"; var assemblyqualifiedname = string.format("myassembly.{0}", typename); var mytype = type.gettype(assemblyqualifiedname); //call activator overload, `instance` system.object var instance = activator.createinstance(mytype); //use reflection invoke method mytype.invokemember( "runcustomfunction", //member name bindingflags.public | bindingflags.instance | bindingflags.static, null, //default binder instance, //actual instance invoke method on null //no arguments use null );
as can see, it's easier make types inherit base class or implement interface, can use reflection if want hard way :)
Comments
Post a Comment