MonoBehavior中得到挂载脚本的各种方法

1.得到自己挂载的单个脚本

//根据脚本名获取
//如果获取失败默认返回空
Test t = this.Getcomponent("脚本名") as Test ;
//根据Type获得
Test t = this.GetComponent(typeof(Test)) as Test;

//根据泛型获取,常用
Test t = this.Component<Test>();

2.得到自己挂载的多个脚本

//用普通数组存储
Test[]array = this.Components<Test>();
//用泛型数组存储
List<Test> = new List<Test>();
this.Components<Test>(list);

3.得到子对象挂载的脚本

寻找子对象挂载的脚本也会默认寻找自身是否挂载该脚本,ComponentInChildren函数的参数默认为false,即如果子对象失活是不会去找子对象挂载的脚本的

//得到单个
Test t = this.ComponentInChildren<Test>(true);
//得到多个
Test[]t=this.ComponentsInChildren<Test>();

List<Test> list = new List<Temp>();
this.ComponentsInChildren<Temp>(true,list);

 4.得到父对象挂载的脚本

//得到单个
Test t = this.ComponentInParent<Test>();

//得到多个
List<Test>list=new list<Temp>();
this.ComponentsInParent<Temp>(list);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值