Unity3D 获得GameObject组件的方法

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

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值