- Home /
Attaching a script at runtime
Hi all,
I would need to add a script to a gameobject based on its name, which is stored in a string. So, for example, if an object called "zombie" enters the field, I have to attach zombie.cs to it.
I was planning on using something like:
gameObject.AddComponent(gameObject.name);
but I've just realized that this method has been deprecated in Unity 5. Now, the script class can only be specified as a generic class.
One possible workaround would be to create a method that explicitly calls AddComponent with the right type for each possible string, but I was wondering it there's a more elegant solution.
So far I've tried:
Type script = Type.GetType(gameObject.name);
gameObject.AddComponent<script>();
and:
gameObject.AddComponent<Type.GetType(gameObject.name)>();
but they both give different compilation errors.
Any idea?
from what I know in unity 4.6 it was:
c#:
gameObject.AddComponent<YourScriptNameOrClassName>();
JS:
gameObject.AddComponent("YourScriptNameOrClassName");
it seems you are mixing the methods.
the script you want to attach derives from monobehavior?
Do you really need to use the string reference to attach your script?
I am not using unity5 yet sorry :p
The gameObject.AddComponent(string) syntax doesn't work any more in Unity 5: http://blogs.unity3d.com/2015/01/21/addcomponentstring-api-removal-in-unity-5-0/ (I wish I had found this before...)
Answer by NoseKills · Mar 31, 2015 at 04:12 PM
In Unity 5 There's a non generic version of AddComponent(Type tp)
too
gameObject.AddComponent(Type.GetType(gameObject.name));
Thank you, that's exactly what I needed! The following code, with a check added as a safety measure, is working as expected:
var scriptAsset = AssetDatabase.FindAssets (cardName);
if (scriptAsset.Length > 0)
{
gameObject.AddComponent(Type.GetType(cardName));
}
else
{
Debug.Log (cardName + " not supported!");
}
If the answer is correct, please click the tickmark next to it to mark this question answered
Answer by astracat111 · Oct 14, 2016 at 05:54 AM
It's "MonoScript" not "script" now, I don't know why.