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();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本