- Home /
Creating a Script at runtime, and adding it to an object...
Hi everyone, I'm using an editorscript to create scripts programmatically (in the editor, not a game). Now, I also am building up a level with this editor script and will need to add the newly created script to a gameobject. Is there any way to do this?
I am well aware that you can still addcomponent with a string by doing something like this:
System.Type t = System.Type.GetType(scriptName);
gameObj.AddComponent<t>();
But the script that I just generated is not in the list of types until I stop the editorscript and run it again. I'm guessing that the types get loaded on compile time, but is there a ways to "refresh" the System.Types during runtime, just like you can do an AssetDatabase.Refresh() at runtime?
Thanks!
Use:
System.Type t = System.Type.GetType(scriptName);
Component c = gameObj.AddComponent(t);
Scripts are asset but you cant load then at runtime, only in editor mode. In this case AssetDatabase.Refresh() should work.
Thanks for the response, but as I mentioned in my post, AssetDatabase.Refresh doesn't work. :(
I did find the following, which highlights the issue. I'm currently working to see if I can figure out a solution that works for my situation...
http://stackoverflow.com/questions/23795173/notification-when-assetdatabase-refresh-is-ready
Thanks!
Answer by Jonesy19 · Oct 13, 2016 at 04:00 PM
In case anyone is wondering, I got around my solution by doing the following (from the link in my comment above. I created a function and added [DidReloadScripts] to the top. That function will be run whenever the scripts are reloaded. For my purposes, that worked.
[DidReloadScripts]
public static void addComponentOnReload()
{
Debug.Log("Reloading Scripts...");
GameObject obj = GameObject.Find("LevelController");
System.Type t = System.Type.GetType("xyz");
Component c = obj.GetComponent<xyz>();
if (c == null)
{
c = obj.AddComponent(t);
Debug.Log("Added Component Event_sheet_1 to LevelController...");
}
}