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"));
 }
 }

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.

@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?