- Home /
Runtime Add/Remove C# Script
Hello everyone,
I have stored the DestoryOnTouch.cs under "Scripts/ButtonPop_Controll/", the DestoryOnTouch.cs used to destory the object on touch and it is work if i add the script in unity editor, not runtime.
I have added the code shown as below in a parent node object named Workstation, there are number of child object, so i using a for loop to add the DestoryOnTouch.cs in runtime
However,it is not work, anyone can help me find the problem?
Thank you.
if(mDele)
{ int childs = transform.childCount;
for (int i = childs - 1; i >= 0; i--)
{ transform.GetChild(i).gameObject.AddComponent("Scripts/ButtonPop_Control/DestoryOnTouch");
}
}
if(!mDele)
{ int childs = transform.childCount;
for (int i = childs - 1; i >= 0; i--)
{ GameObject.Destroy(transform.GetChild(i).gameObject.GetComponent("Scripts/ButtonPop_Controll/DestoryOnTouch"));
}
}
Answer by whydoidoit · Feb 16, 2014 at 04:19 PM
AddComponent and GetComponent use the name of the class in the script, not a path to the script.
AddComponent("DestroyOnTouch");
Or preferably:
AddComponent<DestroyOnTouch>();
As this will give you a compile time error if the class cannot be found, rather than a runtime error.
Answer by Tanoshimi2000 · Jun 27, 2018 at 12:00 PM
@whydoidoit Not intending to hijack this thread, but since it's here, I don't want to start a new one and get scolded.
2018 took away the ability to use a string for the AddComponent function. How would I be able to load a script at runtime, if I don't know what the name of the script is?
I have an XML with a list of powers. When the player selects on, I need the script for that power added in so that when they press the button to activate their power, that script is called.
Any suggestions?
Well if you read the docs on AddComponent you ll notice it takes as a parameter a Type var so, assu$$anonymous$$g you have the name(string) of said Type you should do something like this
System.Type mType = System.Type.GetType("mTypeNameString");
AddComponent(mType);
Well that works. I had read the documentation, but I've never used GetType before, so that's the part I didn't get. The problem now, is that I cannot call any of the functions or methods of that script. AddComponent returns a Component, and so I cannot use: GetComponent(mType).Fire();
Hi Tanoshimi - I've just stumbled across this thread looking for info on something else and I expect you've long since solved your issue but for anyone else you need to cast your component to the right type, so you could say (($$anonymous$$ySpellScript)GetComponent(mType)).Fire();