您的位置:首页 > 移动开发 > Unity3D

Unity3D 获得GameObject组件的方法

2015-12-20 13:56 453 查看
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: