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);
}
}
}
To access a
Component
from a Unity3dGameObject
, you should use theGameObject.GetComponent<T>()
method. There is more than one way to do this.From your example code, there are a few things that should really be addressed:
GameObject.Find("Cube");
will only find a single object named "Cube" in the heirarchy. You should useFindObjectsOfType<MyScript>()
if you want to find allGameObjects
that have theMyScript
component (FindObjectOfType
if you only want to find 1)Based on that, you can get to the variables of
MyScript
like this:or if you want to check the status of all
MyScript
active components: