由于是同一物体上的组件,所以不需要用 GameObject.Find() 来寻找物体,直接可以获取需要的组件来调用。
如物体 B06_Ch_04_Avatar 上的组件脚本 scriptB 调用组件 Transform 的变量:
public class scriptB : MonoBehaviour
{
public Transform ts;
void Start () {
ts = GetComponent();
}
private void OnGUI()
{
if (GUILayout.Button("左旋"))
{
ts.SetPositionAndRotation(new Vector3(0, 0, 0), Quaternion.Euler(0, 90, 0));
}
if (GUILayout.Button("正面"))
{
ts.SetPositionAndRotation(new Vector3(0, 0, 0), Quaternion.Euler(0, 0, 0));
}
if (GUILayout.Button("右旋"))
{
ts.SetPositionAndRotation(new Vector3(0, 0, 0), Quaternion.Euler(0, -90, 0));
}
}
}
当组件在不同的物体上时,需要先用 GameObject.Find() 来寻找组件所在的物体,然后才能进行调用。
1、在Unity中常常会用一个物体的脚本,来调用另一个物体的脚本中的某一变量。此时是不同的物体。如物体 A 上有一个脚本 scriptA ,物体B上有一个脚本 scriptB。现在物体B上的脚本 scriptB 要调用物体 A 上的脚本 scriptA 中的一个变量值。其实现方法如下
// A物体上的脚本 scriptA
public class scriptA : MonoBehaviour
{
public int a1=100;
}
// B物体上的脚本 scriptB
public class scriptB : MonoBehaviour
{
public GameObject obj1;
public scriptA sc;
void Start () {
obj1 = GameObject.Find("A");
// 尤其注意GetComponent<> 和 GetComponents<>的区别
// GetComponents<>方括号中的参数是一个数组的形式
sc = obj1.GetComponent();
Debug.Log(sc.a1);
}
}
运行时显示结果如下:
2、物体B 上的脚本调用物体 B06_Ch_04_Avatar 的Transform 组件中的变量:
// 物体B上的脚本 scriptB
public class scriptB : MonoBehaviour
{
public GameObject obj2;
public Transform ts;
void Start () {
obj2 = GameObject.Find("B06_Ch_04_Avatar");
ts = obj2.GetComponent();
}
private void OnGUI()
{
if (GUILayout.Button("左旋"))
{
ts.SetPositionAndRotation(new Vector3(0, 0, 0), Quaternion.Euler(0, 90, 0));
}
if (GUILayout.Button("正面"))
{
ts.SetPositionAndRotation(new Vector3(0, 0, 0), Quaternion.Euler(0, 0, 0));
}
if (GUILayout.Button("右旋"))
{
ts.SetPositionAndRotation(new Vector3(0, 0, 0), Quaternion.Euler(0, -90, 0));
}
}
}
运行结果如下:
【注意】:
1、GetCompoment
2、GetCompomentInChildren
3、GetComponents
4、GetComponentsInChildren
5、GetComponentsInChildren
MyComponment myCom=gameObject.GetComponent();
MyComponment childCom=gameObject.GetComponentInChildren();
MyComponment[] comS=gameObject.GetComponents();
MyComponment[] comS1=gameObject.GetComponentsInChildren();
MyComponment[] comSTrue=gameObject.GetComponentsInChildren(true);
MyComponment[] comSFalse=gameObject.GetComponentsInChildren(false);
参考资料:
[1] 同一个场景不同物体传值问题 2 回复 1071 查看 打印 上一主题 下一主题