Access dynamically added Component in Unity3d C#

2019-09-08 17:05发布

问题:

After adding a Component to a GameObject via the GameObject.AddComponent method, how can I access this Component from another script?


here is myScript code (not attach to a GameObject):

using UnityEngine;
using System.Collections;

public class MyScript : MonoBehaviour {
    public string       myName = "myName";
    public Vector3      pos;
    public bool         visible;
}

and here is the main code attached to a gameobject in the scene:

using UnityEngine;
using System.Collections;

public class Main : MonoBehaviour {
    public GameObject cube;

    void Update() {
        if(Input.GetKeyDown(KeyCode.Space)) {
            cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.AddComponent<MyScript>();
        }

        if(Input.GetKeyDown(KeyCode.LeftShift)) {
            var a = GameObject.Find("Cube");

            print("cube name/visible: " + 
            /* here is the problem, how do i access the MyScript variables? */ 
            a.myName + "/" + a.visible);
        }
    }
}

回答1:

To access a Component from a Unity3d GameObject, you should use the GameObject.GetComponent<T>() method. There is more than one way to do this.

MyScript m = gameObject.GetComponent<MyScript>();
MyScript m = gameObject.GetComponent("MyScript") as MyScript;
MyScript m = (MyScript) gameObject.GetComponent(typeof(MyScript));

From your example code, there are a few things that should really be addressed:

  • If you want to create components in your scene dynamically, it is better practice to create a prefab, then add that into your scene
  • If you are planning to add large amounts of objects into your scene at runtime, you should use pooling, rather than expensive creating and destroying objects
  • GameObject.Find("Cube"); will only find a single object named "Cube" in the heirarchy. You should use FindObjectsOfType<MyScript>() if you want to find all GameObjects that have the MyScript component (FindObjectOfType if you only want to find 1)

Based on that, you can get to the variables of MyScript like this:

MyScript a = FindObjectOfType<MyScript>();
print(a.myName + "/" + a.visible);

or if you want to check the status of all MyScript active components:

MyScript[] myScripts = FindObjectsOfType<MyScript>();
foreach (MyScript myScript in myScripts) {
    print(myScript.myName + "/" + myScript.visible);
}