Hello,
I have like 50 different scripts for different camera effects.
I want to make a generic script prefab with inspector to allow to drag and drop the effect i want to use for a specific level.
Currently i allow to add a string of the script name, like:
System.Type MyScriptType = System.Type.GetType(StringOfMyScriptName + ",Assembly-CSharp");
Component effectInstance = Camera.main.gameObject.AddComponent(MyScriptType);
Which actually adds the script to the main camera.
My issue is that i can’t access the script public parameters, like enabled, or effect values or maybe i am using a wrong method to handle the effects.
Hi. You won’t know this information unless you create an interface for that type. You are creating an instance of the object at runtime but at design the type information isn’t available because it’s not declared anywhere.
To access the properties of the class you should bind it to an interface which provides an abstract definition for you.
For example:
public interface IMyClass
{
public string MyProperty {get;set;}
public void MyFunction();
}
public MyClass : Monobehaviour, IMyClass
{
//implementation of IMyClass
}
Your code:
System.Type myType = System.Type.GetType(myClassString +" , Assembly-CSharp");
var myInstance = (IMyClass)Camera.main.gameObject.AddComponent(myType);
However, Unity doesn’t play nice with interfaces, since interfaces do not allow fields to be defined, only properties and Unitys inspector will not serialize properties.
But you’ll be able to work around that by using property backing fields in your implementation.
Also since your class is declared in a seperate assemmbly, your calling assembly will need a reference to the interface and so will the assembly with your implementation. Basically an interface provides the bridge between the implementation and the consumption of your class.