GetComponent() - Is it possible to pass a string variable as name of the script?

Newbie here, with excuses in advance if it was already answered or explained in some documents. Evidently I can’t get it, even after reading severals posts and API’s GetComponent() manual pages, I’ve solved nothing and I’m now more confused.

I have different Gameobjects with scripts on them all named like Cube1_MyScript, Cube2_MyScript, and so on.

I would like to access scripts passing their names as string variable to GetComponent(), if feasible. Something like this:

    public class Test : MonoBehaviour {       
          public Myscript script;
          void Update() {  [cut]

            objectname =;
            scriptname = objectname+"_MyScript"; // In order to have Cube1_MyScript
            script = GameObject.Find(objectname).GetComponent<scriptname>();
            script.MyVarBool = true;

This code obiouvsly doesn’t work, just like several other that I’ve wrote, unfortunately I can’t figure out alone if there’s any way to get over this.

Thanks in advance for pointing out any info or help - will be very appreciated.

Check the docs.

The third listing for GetComponent is:

Component GetComponent(string type);

Here is the example:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public HingeJoint hinge;
    void Example() {
        hinge = gameObject.GetComponent("HingeJoint") as HingeJoint;
        hinge.useSpring = false;

After spending a few hours searching, I found the solution. Here is a small script that I made :slight_smile:

This will create an array of Strings where you can write the names of the scripts you want to activate.

var MyScriptNames: String[];

    function Start(){
    for(var i : int = 0; i < MyScriptNames.Length; i++)
     	(gameObject.GetComponent(MyScriptNames*) as MonoBehaviour).enabled = true;*
  • }*

I asked a similar question some time ago HERE