Unity同一场景中不同组件间的调用

一、同一物体(GameObject)的组件之间进行相互调用

由于是同一物体上的组件,所以不需要用 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)的组件间相互调用

当组件在不同的物体上时,需要先用 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);
	}
}

运行时显示结果如下:

 Unity同一场景中不同组件间的调用_第1张图片

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));
        }
    }
}

运行结果如下:

Unity同一场景中不同组件间的调用_第2张图片

 

【注意】:

1、GetCompoment () 从当前游戏对象获取组件T,只在当前游戏对象中获取,没有就返回null,不会去子物体中去寻找。

2、GetCompomentInChildren() 先从本对象中找,有就返回,没有就去子物体中找,直到找完为止。

3、GetComponents() 获取本游戏对象的所有T组件,返回一个数组。不会去子物体中找。

4、GetComponentsInChildren()=GetComponentsInChildren(true) 取本游戏对象及子物体的所有组件

5、GetComponentsInChildren(false) 取本游戏对象及子物体的所有组件

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 查看 打印 上一主题 下一主题

你可能感兴趣的:(Unity)