Loading script by name in Unity3D

I am creating a C # game with Unity3D, and I need to call the script that I create at runtime, so I know the name of the script because I have an object with the name exactly the same.

I create a script at runtime and then save it in my Resources folder, but then I change the scene and should call it a script and attach it to my Empty GameObject in the current scene, so I would like to use something like this :

Script myScript = Resources.Load(myObject.name) as Script; 

But I know that this cannot be done this way, so I am looking for a way that I can do what I want, because I need to load this new script in order to add some functions at runtime.

Do you know any solution to my problem? Thank you very much!

+4
source share
1 answer

It is actually easier than you think. You can add a script to the game object using the AddComponent method. So, after your level has changed, you can just grab your empty game object and do:

 var gameObject = ... gameObject.AddComponent<Script>(); // where Script is the name of your Script C# class 

See http://docs.unity3d.com/Documentation/ScriptReference/GameObject.AddComponent.html

+7
source

All Articles