Unity3D 獲得GameObject組件的方法有幾種,這里進行說明一下:
組件:
要獲得這些組件,進行操作的話,綁定一個Movescipt 的C#組件,里面的獲取方法為
void Update () { Debug.LogError("sprite=" + gameObject.GetComponent<SpriteRenderer>().sprite); Debug.LogError("sortingOrder=" + gameObject.GetComponent<SpriteRenderer>().sortingOrder); Debug.LogError("color=" + gameObject.GetComponent<SpriteRenderer>().color); Debug.LogError("position=" + gameObject.GetComponent<Transform>().position); Debug.LogError("rotation=" + gameObject.GetComponent<Transform>().rotation); Debug.LogError("localScale=" + gameObject.GetComponent<Transform>().localScale); Debug.LogError("position=" + gameObject.transform.position); Debug.LogError("rotation=" + gameObject.transform.rotation); Debug.LogError("localScale=" + gameObject.transform.localScale); }
這樣通過獲得組件GetComponent<>方法,能夠獲得一些需要的屬性。
需要說明一下,
GetComponent<Transform>() 和 gameObject.transform 都能夠獲得組件的形態對象,只是寫法不同罷了,推薦第一張寫法,后面的方法估計以后也就是會廢棄。
獲得同一對象下面的其他組件也是同樣的方法。
當要獲得游戲對象下面的字對象的時候,用
shootscript shoot= gameObject.GetComponentInChildren<shootscript>();
就可以得到子對象,也可以用集合的方式得到子對象的集合,進行操作,反之,可以從子對象得到父對象
movescript ms = gameObject.GetComponentInParent<movescript>();
當然,能夠拿到子對象或者父對象的組件了,也可以順帶得到該對象,對該對象進行處理了
GameObject move = gameObject.GetComponentInParent<movescript>().gameObject; Debug.LogError("prant -----move = " + move.transform.position);
當兩個游戲對象是平級的時候,如果要獲得另一個游戲對象的屬性
Find 是獲得的對象名字
Test2 test2 = GameObject.Find("1wwww").GetComponent<Test2>(); test2.SayTest2();
FindGameObjectWithTag 是獲得的游戲對象的Tag,這個是可以自己去定義的,同時,當然可以進行獲得到一個集合了
Test2 test2 = GameObject.FindGameObjectWithTag("Player").GetComponent<Test2>(); test2.SayTest2();
也是同樣的獲得Tag
Test2 test2 = GameObject.FindWithTag("555555").GetComponent<Test2>(); test2.SayTest2();