Question
I would like to load a list of scripts that all extend from one script from a folder within resources. Next, I want to spawn an object, and randomly assign it one of those scripts. Is this possible?
What I’ve tried
So far, I’ve found Resource.LoadAll(), and it has found all the scripts in my folder, however, I’m not sure where to go from there. It seems like all of scripts have the type of UnityEditor.MonoScript when I call script.GetType(), instead of the class that I have created, like MyScript. I thought I was able to add them to a list through casting (list.Add(script as MyScript)), but that is just adding null to the list.
For the second part, I know I have to create an instance of a prefab using Instantiate, and then attach the script using GameObject.AddComponent(). The problem I have facing here is that I don’t know all the types I will be using (since all the scripts are read from a folder). So far, I have something like this:
var prefab = Instantiate(obj, pos, rot) as MyObj; // obj is the prefab, MyObj is the type
var scriptType = myScript.GetType(); // myScript is randomly chosen from the list generated before.
prefab.gameObject.AddComponent(scriptType); // Should add the script to the object, which should do it's magic.
However, I have a warning when instantiating that The referenced script on this Behaviour is missing! since obj does not contain a script to make it a class of MyObj. Next, because my list is full of nulls, I cannot add any scripts, so I can’t tell if I’m doing this part right or not.