Loading a script by name in Unity3D

I’m creating a game in C# with Unity3D and I need to call a script that I create on runtime, so I know the name of the script because I have an object named exactly like it.

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

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

But I know this can’t be done like this, so I’m looking for a way I can do what I want, because I need to load that new script to add some functions on runtime.

Do you know any solution to my problem? Thanks a lot!!

Answer

That’s actually easier than you think. You can add a script to a game object using the AddComponent method. So after your level has changed you can just get hold of your empty game object and do a:

var gameObject = ... 

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *