Is this possible?
I’m creating in runtime a script and saving it in the project but i cannot find the way to get that script and add it to a gameobject via script.
Steps:
Create GameObject via Script
Create Script via Script
*Get the Script created
*Add to the GameObject
The problem is that in that moment MyScript do not exist. Is just a file. Im creating it with the StreamWriter and adding the lines.
If there a way to seach scripts by the name “MyScript.cs” or something like that
I’m developing a ScreenManager where with an editor popup you can create the Screen template. So i create the GameObject, the Prefab and the Script, but i would like to add that script into the prefab so users will not have to drag and drop.
Oh, so it’s not at runtime, its an editor extension?
Well, you still need to build it somehow, after creating the MyScript.cs file, you need to wait for unity to build it and then you will be able to add it. But there’s no onBuild callback I know of…
You’ll have to instruct the user to add the script manually I think, but would love to know if there’s a way for this actually!
I have an editor window where the steps i want to do are:
Create GameObject (done)
Rename it (done)
Create a script in editor runtime (done)
Create the prefab of the GameObject created (done)
Add the script created to the gameobject created (can’t)
I once tried this but ended in tears. You cannot add a script that is created through a script to an object. Unity needs to compile the script before it can be used and, this is not done through a script. Sorry, I tried for maybe 6 1/2 hours one day to no avail.
I’m still not getting why an AddComponent + Reflection combination won’t work. You can use DidReloadScripts to get a call back after compilation is finished. Then you can scan the assembly for the script you just created with Reflection. Then you add the component with AddComponent.
It requires a fair bit of coding know how, I don’t have the time now to do a mock up for you. But if you are writing editor scripts then you should be able to handle it.
Run time compilation is possible on some platforms. Check out Emit. That said most games with run time compilation use an interpreted scripting language like LUA. Its far easier to implement and control.
Edit: Its also worth noting that by putting logic into data that can be parsed by your own system you can often avoid adding new scripts at runtime altogether.
Just be careful on the platforms, I know you can’t use it for iOS. Apple wants to be able to approve every single line of code that runs on their machines. I think the other platforms are mostly okay.
What i did was saving in a .txt the name of my class and doing what i posted up here.
Then scriptName matches with the type.Name and i add it to a GameObject that a created!