【Unity】获取游戏对象

本文详细介绍在Unity中如何操作游戏对象的组件,包括获取RectTransform、Button、Image等组件的方法,以及如何通过Find方法查找子节点并添加监听事件。同时,讲解了如何设置GameObject的活动状态,以及不同方式获取当前游戏对象上的组件。
			RectTransform tr = this.GetComponent<RectTransform>();
            RectTransform rect = (this.transform as RectTransform);

            //直接获得对象身上的其它组件(类)
            Button bb = this.GetComponent<Button>();// ("Panel/center/left/btn_addRoom");
            Image m = this.transform.GetComponent<Image>();

            //获得当前游戏对象下面的其它子节点身上的组件,先找
            //用多行表示
            Transform ttr2 = this.transform;
            Transform ttr3 = ttr2.Find("Panel/center/left/btn_addRoom");
            Button bb0 = ttr3.GetComponent<Button>();
            bb0.onClick.AddListener(()=> {

            });
            //简单表示
            Transform trr =  this.transform.Find("Panel/center/left/btn_addRoom");
            Button bb2 = trr.GetComponent<Button>();
            bb2.onClick.AddListener(() => {

            });
            //改成一句话表示
            this.transform.Find("Panel/center/left/btn_addRoom").GetComponent<Button>().onClick.AddListener(()=> {

            });
            Test t = this.transform.Find("Panel/center/left/btn_addRoom").GetComponent<Test>();
            t.id = 100000;
            t.tName = "lili";
            t.run();

            //通过this获得游戏对象本身
            GameObject obj =  this.gameObject;
            obj.SetActive(true);//设置当前游戏对象为活动的(可见的)
            obj.SetActive(false);//设置为禁用的,(不可见的);

            //this.transform.Find("Panel/center/left/btn_addRoom").GetComponent<Button>();
            this.gameObject.transform.Find("Panel/center/left/btn_addRoom").GetComponent<Button>();


            //获得当前对象身上的组件的几种 方法
            Test t1 = this.GetComponent<Test>();
            Test t2 =  this.transform.GetComponent<Test>();
            this.gameObject.GetComponent<Test>();
            this.gameObject.transform.GetComponent<Test>();


            this,//代表当前类的对象,或所挂的游戏对象(只能获得所挂游戏对象的一部方法或属性)
            this.transform //获得当前所有挂游戏对象的Tansform类
            this.gameObject;//获得当前游戏对象本身,->GameObject游戏对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烧仙草奶茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值