通过Component
方法向GameObject
添加GameObject.AddComponent
后,如何从其他脚本访问此Component
?
这是myScript代码(不附加到GameObject):
using UnityEngine;
using System.Collections;
public class MyScript : MonoBehaviour {
public string myName = "myName";
public Vector3 pos;
public bool visible;
}
这是附加到场景中游戏对象的主要代码:
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);
}
}
}
答案 0 :(得分:1)
要从Unity3d Component
访问GameObject
,您应该使用GameObject.GetComponent<T>()
方法。这样做的方法不止一种。
MyScript m = gameObject.GetComponent<MyScript>();
MyScript m = gameObject.GetComponent("MyScript") as MyScript;
MyScript m = (MyScript) gameObject.GetComponent(typeof(MyScript));
从您的示例代码中,有一些事情应该真正解决:
GameObject.Find("Cube");
只会找到一个名为&#34; Cube&#34;的对象。在heirarchy。如果您想查找包含FindObjectsOfType<MyScript>()
组件的所有GameObjects
(MyScript
,如果您只想查找1),则应使用FindObjectOfType
基于此,你可以像这样找到MyScript
的变量:
MyScript a = FindObjectOfType<MyScript>();
print(a.myName + "/" + a.visible);
或者如果您想检查所有MyScript
个有效组件的状态:
MyScript[] myScripts = FindObjectsOfType<MyScript>();
foreach (MyScript myScript in myScripts) {
print(myScript.myName + "/" + myScript.visible);
}