- Home /
Is there a way to dynamically attach a script to a GameObject during runtime?
What I am looking for is a way to find a script/MonoBehaviour during runtime that can attach to a GameObject as a component dynamically. There could be thousands of these scripts (that is the extreme case), and is noted by an underscore followed by a number (depending on the GameObject used, called "serialNumber" for now). Here is what I have:
//someObject.AddComponent<"_" + serialNummber>();
//someObject.AddComponent(typeof("_" + serialNummber));
I get an error saying that this does not work, but is there another way to do this (and I hope I don't have to hard code this by typing in every single serial number through a switch statement, that would be the worst case scenario). Any help is appreciated.
Answer by revolute · Jul 08, 2015 at 08:53 AM
gameObject.AddComponent(Type.GetType("ScriptName"));
should do the magic.
Oh, and it is System.Type. So either put "using System;" or write System.Type
I am getting an error that reads: "error CS1501: No overload for method GetType' takes
1' arguments"
It wants an assembly name, do I pass in the same serial number to both strings? or is that not advised? (So far when I put the same input into both the type name and the assembly name, it seems to work fine, should I worry about any concerns on both names?)
Ok, I changed it to System.Type (sorry if i am a little slow, I need to reload the page more). But I am getting this warning here: "AddComponent asking for invalid type". I am trying to see why it is doing that right now...
Yep, it is solved, thank you very much for the help. The warning was a problem on my side dealing with the scripts being not found, but it is working as expected.
Your answer
Follow this Question
Related Questions
Access water4 scripts via my script? 1 Answer
Refresh panel with prefab contained value from json that created using array 0 Answers
cannot drag script to player.Guitext error,cannot drag player script to the player in hierarchy 2 Answers
How to add components to other GameObjects through a C# script attached to one? 2 Answers
Creating a GameObject variable without instantiating it? 1 Answer