- Home /
Attach C# Script on runtime
I want to attach a C# script to a GameObject on runtime. The C# script that I want to attach is Instantiated with a GameObject called _RoomController(Clone)
Screenshot 1
Screenshot 2
public string ClonedRoomController = "_RoomController(Clone)";
public GameObject hardpoint1;
public RoomController rc;
// Use this for initialization
void Start () {
var RoomController2 = gameObject.AddComponent(Type.GetType(ClonedRoomController));
RoomController2 = rc;
RoomController2 = gameObject.AddComponent(Type.GetType(ClonedRoomController));
if (rc.currentGameMode == "DOM")
{
hardpoint1.SetActive(true);
Instantiate(hardpoint1, transform.position, transform.rotation);
}
}
I am trying to attach the C# Script with class RoomController to rc. I currently have to attach the script during runtime and hit pause then it works. I want to add the C# Script as soon as I play. The C# script currently is Instantiated with name _RoomController(Clone)
Answer by Commoble · Apr 25, 2017 at 12:08 AM
To create and attach a script to a GameObject, use AddComponent:
RoomController rcScript = hardpoint1.AddComponent<RoomController>();
The above line instantiates a RoomController script, attaches it to the rc GameObject, and stores a reference to it in the newly created rcScript variable.
The best way to use AddComponent is typically the generic version, which is the last variant on the documentation page.