Basically a script as the property of another script.
For example, I have a prefab called “container” and it has the
properties:
public GameObject ValueDisplayPrefab;
public MonoBehaviour valueDisplayBehaviour;
I basically want to just have one number prefab but alter it’s behaviour (eg, ghostly floating, pulsing, etc…)
I know i can do it by using the name, but wanted to do it like this:
if (ValueDisplayPrefab!=null){
valueDisplay = ((GameObject)Instantiate(ValueDisplayPrefab)).GetComponent<TextMesh>();
if (valueDisplayBehaviour!=null) gameObject.AddComponent (valueDisplayBehaviour.name);
etc...
I basically would like to be able to drag the script onto the property “valueDisplayBehaviour”, as i think using it’s name is not so safe.
Is this possible?
Though through reflection and custom editor scripts you could achieve something like it. However I would expect that getting that code to work on some platforms(flash comes to mind) could prove difficult.
Best way to go would be a switch statement that is capable of adding all your effects. Its not dynamic, but it does the job.
Since you would need a new instance of the prefab for each version of the valueDisplayBehavior and would have to drag it onto that prefab each time anyway, you wouldn’t really be saving any time doing that. If you had four valueDisplayBehavior scripts you’d need four instances of the prefab, so you might as well just have four instances with a different script attached as a component to each one.
I would make four prefabs (GhostlyDisplay, PulsingDisplay, etc), and the ValueDisplay would call something like:
SendMessage(“DoDisplayBehavior”);
and then in the four different display behavior scripts, they would each have a method DoDisplayBehavior() that does their specific trick.
the easy way would be just replacing MonoBehaviour with string below. then using the string version of AddComponent.
But you could also get more precise by getting the type first. where the string holds the type of the script then a comma and the assembly name. so something like this:
“NameOfScript, Assembly-CSharp”
you can then use
System.Type type = System.Type.GetType( “NameOfScript, Assembly-CSharp” );
if( type == null ) Debug.LogError( “Invalid type string”, this );
if( !typeof(TargetScriptTypeBaseClass).IsAssignableFrom(type) ) Debug.LogError("The type “+type+ " is not compatible”, this);
Also while i dont recommend doing this you could instead of string use UnityEngine.Object. And be able to assign .cs or .js files to it then use .name to figure out the type for the addcomponent string overload. but even if that worked it could make some weird dependancies on the built player.