Unity中GameObject中的常用方法

1、静态方法

(1)根据对象名(游戏物体)查找对象

cs 复制代码
        GameObject obj2 = GameObject.Find("Holens");
        if( obj2 != null )
        {
            print(obj2.name);
        }
        else
        {
            print("没有找到对应对象");
        }

(2)通过tag来查找对象

cs 复制代码
GameObject obj3 = GameObject.FindWithTag("Player");

(3)查找多个对象

cs 复制代码
GameObject[] objs = GameObject.FindGameObjectsWithTag("Player");
print("找到tag为Player对象的个数" + objs.Length);

!!!注意:这些方法都无法找到失活的对象!!!

(4)摧毁对象

cs 复制代码
        GameObject.Destroy(myObj2);
        //第二个参数 代表延迟几秒钟删除
        GameObject.Destroy(obj5, 5);
        //Destroy不仅可以删除对象 还可以删除脚本
        GameObject.Destroy(this);

如果类继承了Mono,那可以不写GameObject

2、成员方法

(1)为对象添加脚本

cs 复制代码
Lesson2 les2 = obj6.AddComponent<Lesson2>();

(2)标签比较

cs 复制代码
        if(this.gameObject.CompareTag("Player"))
        {
            print("对象的标签 是 Player");
        }

(3)设置激活失活

cs 复制代码
obj6.SetActive(false);
obj6.SetActive(true);
相关推荐
DaLiangChen15 小时前
Vuforia 地面识别案例
unity·ar
江畔柳前堤21 小时前
YOLO 目标检测全流程深度剖析
人工智能·yolo·目标检测·计算机视觉·unity·面试·vllm
魔术师Dix1 天前
一个轮子:Luban Skill 制作演示
游戏·unity·ai编程
xcLeigh2 天前
Unity基础:Light灯光组件入门——Directional Light、Point Light与Spotlight
unity·游戏引擎·教程
郝学胜-神的一滴2 天前
[简化版 GAMES 104] 现代游戏引擎 04:从0到1构建你的游戏世界
c++·游戏·unity·游戏引擎·软件工程·unreal engine
是嘟嘟啊3 天前
【Unity DOTS】EntityCommandBuffer 与 JobHandle
unity·ecs·dots·unity dots·job·burst·burstjob
xcLeigh3 天前
Unity基础:Camera相机组件详解——透视投影与正交投影的区别
数码相机·unity·游戏引擎
玖玥拾3 天前
Unity3D RPG 入门项目(二)移动 Bug 修复、环绕相机、NPC 任务系统、UI 穿透处理
unity·游戏引擎
Yasin Chen3 天前
Unity UGUI RectMask2D 原理
unity·游戏引擎