- Home /
Load a list of scripts from folder
Question
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
o 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 null
s, I cannot add any scripts, so I can't tell if I'm doing this part right or not.
Answer by mattssheep4 · Mar 28, 2020 at 12:16 PM
Should be doable, see this link: https://answers.unity.com/questions/1175014/add-all-scripts-in-a-folder-to-a-gameobject-at-run.html
Based on that thread I think you need to use .Class() instead of .GetType().
Your answer
Follow this Question
Related Questions
Instantiate(GameObject) VS Instantiate(Resource.Load(Object Path)) 1 Answer
[Solved] How to Dynamicaly assemble an Object in your Resource Folder 1 Answer
resources.load (instantiate from this.transform) rather then the centre of the map? 1 Answer
Picture loaded from resource corrupted. 0 Answers
Problem with AddComponet(SCRIPT) on a Instantiated PREFAB 0 Answers