Unity2019.3API教程(三)GameObject类

2023-11-11

GameObject类

1. 官方定义

class in UnityEngine/Inherits from:Object/Implemented in:UnityEngine.CoreModule
属于 UnityEngine命名空间下的类,继承于Object类,和Object类一样是UnityEngine.CoreModule下的核心模块类。

2.官方描述
Base class for all entities in Unity Scenes.

Note: Many variables in the GameObject class have been removed. To access, for example GameObject.renderer in csharp use GetComponent() instead.

See Also: Component.
上述说明GameObject类是Unity场景中所有实体的基类,也就是说Unity场景中物体的创建要通过此类来进行创建。官方后面给了注释,是因为API的弃用,主要是因为4.0X到5.0X以后版本的巨大改变,此处我们不需考虑,后面的代码我会用最新的写法进行解释,按照新版本API的写法用即可,同样的Compent类也有很大改变。

3.属性
activeInHierarchy:Defines whether the GameObject is active in the Scene.
语法:public bool activeInHierarchy;
该属性表示物体的激活状态,当然涉及到子类和父类物体,这里不做解释,我们结合下面的activeSelf属性进行对比解释。

activeSelf:The local active state of this GameObject. (Read Only)
语法:public bool activeSelf;
activeSelf表示物体自身的激活状态,与activeInHierarchy不同的是,activeSelf不受父物体的影响,如果有一个子类和父类物体,父类和子类都激活时,activeSelf和activeInHierarchy输出则都为true,如果父类不激活而子类激活,则我们查看子类激活状态时,activeSelf为true而activeInHierarchy为false,演示如下:

using UnityEngine;

public class ACTest : MonoBehaviour
{
    public GameObject Parent, Child;
    
   
    void Start()
    {
        Parent.SetActive(false);
        Child.SetActive(true);

        Debug.Log(Parent.activeSelf);
        Debug.Log(Parent.activeInHierarchy);
        Debug.Log(Child.activeSelf );
        Debug.Log(Child.activeInHierarchy);
    }
}

上述代码定义了两个物体,我们需要在场景中创建两个物体,并关联为父子物体,再通过SetActive方法将父物体关闭,子物体激活,注意定义public对象后要在Inspector面板中对物体进行获取,最后进行控制台打印结果,可得我们上述结论。

isStatic:Gets and sets the GameObject’s StaticEditorFlags.
语法:public bool isStatic;
该属性表示物体是否为静态,该属性比较好理解,此处不做代码演示,Unity为了对性能进行优化时需要对场景进行烘培,而烘培对象必须设置为静态,一般都是在场景编辑时在Inspector面板进行勾选,当然你可通过控制台打印输出查看物体是否为静态。

layer:The layer the game object is in.
语法:public int layer;
该属性为int型变量,表示游戏物体所在的层,层可用于从摄影机进行选择性渲染或忽略光线投射。Unity可生成32层,默认使用8层,当然也可以根据情况进行更改,我们在Inspector面板可以设置和查看,演示如下:

using UnityEngine;

public class LyTest : MonoBehaviour
{
    
        void Start()
    {
        GameObject go = new GameObject();
        Debug.Log(go.layer);
    }
    
}

scene:Scene that the GameObject is part of.
语法:public SceneManagement.Scene scene;

该属性表示游戏对象所属的场景,因为使用SceneManagement.Scene类进行创建,我们在SceneManagement类教程中在做分析。

tag:The tag of this game object.
语法:public string tag;
该方法表示物体标签,Unity官方强调不要在Awake方法或OnValidate方法设置标签,因为组件唤醒的顺序不确定,可能会出现覆盖等情况,导致消息无法传递,该属性比较简单,不做赘述。

transform:The Transform attached to this GameObject.
语法:public Transform transform;
该属性为Transform类定义,用于表示游戏对象的转换方位等,演示如下:


```csharp
using UnityEngine;

public class TFTest : MonoBehaviour
{
    void Start()
    {
        gameObject.transform.Translate(1, 1, 1);
    }
}

4.构造方法
GameObject:Creates a new game object, named name.
语法:public GameObject();
public GameObject(string name);
public GameObject(string name, params Type[] components);


```csharp
using UnityEngine;

public class GOTest : MonoBehaviour
{
  
    void Start()
    {
        GameObject go = new GameObject("hello",typeof(Rigidbody));
    }

}

5.公有方法
AddComponent:Adds a component class named className to the game object.
语法:public Component AddComponent(Type componentType);
public Component AddComponent(Type componentType);
将名为className的组件类添加到游戏对象中,注意没有RemoveComponent()方法,删除组件用Destroy方法,该方法重载,可通过Type传递参数或者是使用泛型,演示如下:

using UnityEngine;

public class ATTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameObject go = new GameObject();
        go.AddComponent(typeof(Rigidbody)) ;
        go.AddComponent<MeshCollider>();
    }
}

BroadcastMessage:Calls the method named methodName on every MonoBehaviour in this game object or any of its children.
语法:public void BroadcastMessage(string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
该方法表示向自身或者子物体传送消息,有三个参数,methodName是方法名,parameter为对象,SendMessageOptions.RequireReceiver为没有接收到消息是否打印报错,演示如下:

public class _2 : MonoBehaviour
{
    
    // Start is called before the first frame update
    void Start()
    {
        gameObject.BroadcastMessage("Receive");
    }
}
using UnityEngine;

public class _3 : MonoBehaviour
{
    private void  Receive()
    {
        Debug.Log("receive");
    }

}

此处注意要在场景中设置父子物体,因该方法跟SendMessage和SendMessageUpwards有关联,所以设置三层物体,也就是父子孙关系,分别命名_01,_02,_03,对应相应代码块。

CompareTag:Is this game object tagged with tag ?
语法:public bool CompareTag(string tag);
该方法用于判断物体的标签是否为目标标签,并返回一个bool值,参数为string类型的tag,演示如下:

using UnityEngine;

public class CTTest : MonoBehaviour
{
   
   
    void Start()
    {
        GameObject go = new GameObject();

        if(go.CompareTag("Player"))
        {
            Debug.Log("true");
        }
        else
        {
            Debug.Log("false");
        }

    }

    
}

GetComponent:Returns the component of Type type if the game object has one attached, null if it doesn’t.
语法:public Component GetComponent(Type type);
public T GetComponent();
public Component GetComponent(string type);
该方法重载,有三种写法,用于访问获取组件,在Unity中只有拿到了组件,才可以对组件进行访问,演示如下:

using UnityEngine;

public class GTTest : MonoBehaviour
{
    void Start()
    {
        GameObject go = new GameObject();
        go.AddComponent(typeof(Rigidbody));
        go.GetComponent(typeof(Rigidbody));
        go.GetComponent<Rigidbody>();
        go.GetComponent("Rigidbody");
    }
}

GetComponentInChildren:Returns the component of Type type in the GameObject or any of its children using depth first search.
语法:public Component GetComponentInChildren(Type type);
public Component GetComponentInChildren(Type type, bool includeInactive);
public T GetComponentInChildren(bool includeInactive = false);
该方法重载,用于获取子物体组件,includeInactive表示将物体设置为激活状态,如果不设置为激活状态,将无法获取组件,演示如下:

using UnityEngine;

public class GetComponentInChildrenExample : MonoBehaviour
{
    // Disable the spring on the first HingeJoint component found on any child object

    void Start()
    {
        HingeJoint hinge = gameObject.GetComponentInChildren(typeof(HingeJoint)) as HingeJoint;

        if (hinge != null)
            hinge.useSpring = false;
        else
        {
            // Try again, looking for inactive GameObjects
            HingeJoint hingeInactive = gameObject.GetComponentInChildren(typeof(HingeJoint), true) as HingeJoint;

            if (hingeInactive != null)
                hingeInactive.useSpring = false;
        }
    }
}

上述代码,摘自官方示例。

GetComponentInParent:Returns the component of Type type in the GameObject or any of its parents.
语法:public Component GetComponentInParent(Type type);
public T GetComponentInParent();
该方法用于获取父物体的组件,有关Component获取的方法大致相同,代码示例将全部摘自官方示例:

using UnityEngine;
using System.Collections;

public class GetComponentInParentExample : MonoBehaviour
{
    // Disable the spring on the first HingeJoint component found on any parent object

    void Start()
    {
        HingeJoint hinge = gameObject.GetComponentInParent(typeof(HingeJoint)) as HingeJoint;

        if (hinge != null)
            hinge.useSpring = false;
    }
}

GetComponents:Returns all components of Type type in the GameObject.
语法:public Component[] GetComponents(Type type);
public T[] GetComponents();
public void GetComponents(Type type, List results);
public void GetComponents(List results);
该方法用于得到一组同样类型的组件,返回的是一个数组或者是链表,演示如下:

// Disable the spring on all HingeJoints in this game object
using UnityEngine;

public class GetComponentsExample : MonoBehaviour
{
    // Disable the spring on all HingeJoints in this game object

    void Start()
    {
        Component[] hingeJoints;

        hingeJoints = GetComponents(typeof(HingeJoint));

        foreach (HingeJoint joint in hingeJoints)
            joint.useSpring = false;
    }
}
// Disable the spring on all HingeJoints in this game object
using UnityEngine;
using System.Collections.Generic;

public class GetComponentsExample : MonoBehaviour
{
    // Disable the spring on all HingeJoints in this game object

    void Start()
    {
        // Disable the spring on all HingeJoints in this game object
        List<Component> hingeJoints = new List<Component>();

        GetComponents(typeof(HingeJoint), hingeJoints);

        foreach (HingeJoint joint in hingeJoints)
            joint.useSpring = false;
    }
}

GetComponentsInChildren:Returns all components of Type type in the GameObject or any of its children.
语法:public Component GetComponentInChildren(Type type);
public Component GetComponentInChildren(Type type, bool includeInactive);
public T GetComponentInChildren(bool includeInactive = false);
获取子物体的一组组件,注意物体要处于激活状态,演示如下:

using UnityEngine;

public class GetComponentInChildrenExample : MonoBehaviour
{
    // Disable the spring on the first HingeJoint component found on any child object

    void Start()
    {
        HingeJoint hinge = gameObject.GetComponentInChildren(typeof(HingeJoint)) as HingeJoint;

        if (hinge != null)
            hinge.useSpring = false;
        else
        {
            // Try again, looking for inactive GameObjects
            HingeJoint hingeInactive = gameObject.GetComponentInChildren(typeof(HingeJoint), true) as HingeJoint;

            if (hingeInactive != null)
                hingeInactive.useSpring = false;
        }
    }
}

GetComponentsInParent:Returns all components of Type type in the GameObject or any of its parents.
语法:public Component[] GetComponentsInParent(Type type, bool includeInactive = false);
public T[] GetComponentsInParent();
public T[] GetComponentsInParent(bool includeInactive);
public void GetComponentsInParent(bool includeInactive, List results);
该方法用于返回父物体的一组组件,为数组或者链表,注意设置物体的额激活状态,演示如下:

using UnityEngine;

public class GetComponentsInParentExample : MonoBehaviour
{
    void Start()
    {
        Component[] hingeJoints;

        hingeJoints = GetComponentsInParent(typeof(HingeJoint));

        if (hingeJoints != null)
        {
            foreach (HingeJoint joint in hingeJoints)
                joint.useSpring = false;
        }
        else
        {
            // Try again, looking for inactive GameObjects
            Component[] hingesInactive = GetComponentsInParent(typeof(HingeJoint), true);

            foreach (HingeJoint joint in hingesInactive)
                joint.useSpring = false;
        }
    }
}

SendMessage:Calls the method named methodName on every MonoBehaviour in this game object.
语法:public void SendMessage(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
该方法表示向自身发送消息,有三个参数,与BroadcastMessage一样,value表示‎要传递给被调用方法的可选参数值,演示如下:

using UnityEngine;

public class _2 : MonoBehaviour
{
    void Start()
    {
        gameObject.SendMessage("Receive");
    }
}

using UnityEngine;

public class _0 : MonoBehaviour
{
   private void Receive()
    {
        Debug.Log("receive");
    }
}

SendMessageUpwards:Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.
语法:public void SendMessageUpwards(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
该方法表示向自身及父类发送消息,参数同SendMessage,演示如下:

using UnityEngine;

public class _2 : MonoBehaviour
{
    private void Start()
    {
        gameObject.SendMessageUpwards("Receive");
    }
}

using UnityEngine;

public class _1 : MonoBehaviour
{
    private void Receive()
    {
        Debug.Log("receive");
    }
}

SetActive:Activates/Deactivates the GameObject, depending on the given true or false value.
语法:public void SetActive(bool value);
该方法用于激活物体,前面已经介绍过,不再赘述。

TryGetComponent:Gets the component of the specified type, if it exists.
语法:public bool TryGetComponent(Type type,out Component compomemt)
public bool TryGetComponent(out T component);
该方法表示查找获取指定类型的组件,与GameObject.GetComponent相比,若查找组件不存在时将不会在编辑器中进行分配,演示如下:

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour
{
    void Start()
    {
        if (gameObject.TryGetComponent(typeof(HingeJoint), out Component component))
        {
            component.name = "My Hinge";
        }
    }
}

6.静态方法
CreatePrimitive:Creates a game object with a primitive mesh renderer and appropriate collider.
语法:public static GameObject CreatePrimitive(PrimitiveType type);
用于根据指定类型创建物体,该方法如果在使用时没有引用MeshFilter、meshfrenderer和BoxCollider或spherecollier组件,会出现创建失败的情况,避免的建议方法是声明这些类型的私有属性,剥离系统将识别它们的用途,并将它们包含在构建中,因此不会删除这些组件,示例如下:

using UnityEngine;

public class Example : MonoBehaviour
{
    // Create a plane, sphere and cube in the Scene.

    void Start()
    {
        GameObject plane  = GameObject.CreatePrimitive(PrimitiveType.Plane);

      
    }
 }

Find:Finds a GameObject by name and returns it.
语法:public static GameObject Find(string name);
按名称查找游戏对象并返回它,此函数只返回活动的游戏对象,如果找不到名称为的GameObject,则返回null,如果名称包含“/”字符,则它将像路径名称一样遍历层次结构。出于性能原因,建议不要每帧都使用此功能。相反,在启动时将结果缓存到成员变量中。或者使用GameObject.FindWithTag。如果你想找到一个子游戏对象,通常使用Transform.find更容易;如果游戏运行时有多个场景,那么Find将搜索所有场景。
演示如下:

using UnityEngine;

public class FTest : MonoBehaviour
{
    public GameObject go;

    void Start()
    {
        GameObject  gb =new GameObject("Cube";
        go = GameObject.Find("Cube");
    }
}

FindGameObjectsWithTag:Returns an array of active GameObjects tagged tag. Returns empty array if no GameObject was found.
语法:public static GameObject[] FindGameObjectsWithTag(string tag);
该方法用于通过标签查找一组物体,代码示例如下:

// Instantiates respawnPrefab at the location
// of all game objects tagged "Respawn".

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public GameObject respawnPrefab;
    public GameObject[] respawns;
    void Start()
    {
        if (respawns == null)
            respawns = GameObject.FindGameObjectsWithTag("Respawn");

        foreach (GameObject respawn in respawns)
        {
            Instantiate(respawnPrefab, respawn.transform.position, respawn.transform.rotation);
        }
    }
}

FindWithTag:Returns one active GameObject tagged tag. Returns null if no GameObject was found.
语法:public static GameObject FindWithTag(string tag);
该方法为通过标签查找单个物体,但是返回使用指定标签找到的第一个GameObject,如果场景包含多个具有指定标签的GameObjects,则无法保证此方法将返回特定GameObject,注意是非静态的物体,代码演示如下:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public GameObject respawnPrefab;
    public GameObject respawn;
    void Start()
    {
        if (respawn == null)
            respawn = GameObject.FindWithTag("Respawn");

        Instantiate(respawnPrefab, respawn.transform.position, respawn.transform.rotation);
    }
}

后续的官方说明为继承的属性和方法,因为GameObject类继承Object类,在之前已经讨论过,这里不在赘述。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Unity2019.3API教程(三)GameObject类 的相关文章

随机推荐

  • MySQL数据库总结 之 函数命令总结

    MySQL命令语句中的函数包含四种 字符串函数 数值函数 日期函数 流程函数 前两篇关于MySQL的博客 地址如下 MySQL数据库 SQL语言命令总结 数据类型 运算符和聚合函数汇总 Flying Bulldog的博客 CSDN博客htt
  • (附源码)计算机毕业设计SSM疫情隔离便民系统

    项目运行 环境配置 Jdk1 8 Tomcat7 0 Mysql HBuilderX Webstorm也行 Eclispe IntelliJ IDEA Eclispe MyEclispe Sts都支持 项目技术 SSM mybatis Ma
  • 字符串中找出连续最长数字串(两种题型)--C++

    题目描述一 读入一个字符串str 输出字符串str中的连续最长的数字串 输入描述 个测试输入包含1个测试用例 一个字符串str 长度不超过255 输出描述 在一行内输出str中里连续最长的数字串 输入 abcd12345ed125ss123
  • 安装xposed(解决xposed问题)

    科学上网可轻松解决本文的问题 经过测试leidian mumu yeshen三个模拟器的最新版本只有leidian安装完成后可以重启 其他两个均会卡99 模拟器再起不能 MuMu模拟器win版 版本 2 1 3 可以 安装xposed前需关
  • 面试必备—MySQL中数据查询语句

    一 基本概念 查询语句 基本语句 1 select from 表名 可查询表中全部数据 2 select 字段名 from 表名 可查询表中指定字段的数据 3 select distinct 字段名 from 表名 可对表中数据进行去重查询
  • 使用XStream实现Java对象与XML互相转换(不断更新中)

    添加pom依赖
  • 学习周报-2023-0210

    文章目录 一 在SUSE11sp3系统中将openssh从6升级到8 一 需求 二 系统环境 三 部署流程 1 上传编译安装的软件包 2 安装 gcc编译软件 3 安装依赖zlib 4 安装依赖openssl 5 安装openssh 二 在
  • 华为OD机试真题- 战场索敌-2023年OD统一考试(B卷)

    题目描述 有一个大小是NxM的战场地图 被墙壁 分隔成大小不同的区域 上下左右四个方向相邻的空地 属于同一个区域 只有空地上可能存在敌人 E 请求出地图上总共有多少区域里的敌人数小于K 输入描述 第一行输入为N M K N表示地图的行数 M
  • 8-js高级-2

    JavaScript 进阶 2 了解面向对象编程的基础概念及构造函数的作用 体会 JavaScript 一切皆对象的语言特征 掌握常见的对象属性和方法的使用 深入对象 内置构造函数 综合案例 深入对象 了解面向对象的基础概念 能够利用构造函
  • TesseractEngine

    URL http download csdn net download fuxuan928 4068683 GOOGLE https code google com p tesseractdotnet 下面识别OCR验证码用 NET来实现
  • 使用Python爬虫定制化开发自己需要的数据集

    在数据驱动的时代 获取准确 丰富的数据对于许多项目和业务至关重要 本文将介绍如何使用Python爬虫进行定制化开发 以满足个性化的数据需求 帮助你构建自己需要的数据集 为数据分析和应用提供有力支持 1 确定数据需求和采集目标 在开始定制化开
  • QT学习—五种直接连接信号槽的连接方式

    一 信号与槽机制 特别鸣谢B站大轮明王讲Qt的讲解 大轮明王讲Qt的个人空间 哔哩哔哩 bilibili 信号与槽机制 Signal and Slot 是一种在软件开发中广泛使用的通信机制 主要用于处理事件驱动的程序设计 它是Qt框架中的一
  • 使用 Spot 低成本运行 Job 任务

    作者 代志锋 云果 阿里云技术专家 导读 本节课程有三部分内容 首先阐述 ECI 支持成本优化的几种方式 然后重点介绍 Spot 实例是什么以及如何采用 Spot 实例进行成本优化 最后总结 Spot 实例支持的场景以及注意事项 成本优化
  • 基于JWT token认证机制和基于session认证机制

    基于session认证机制 http协议本身是一种无状态的协议 而这就意味着如果用户通过应用向服务器提供了用户名和密码进行认证 下一次请求时 用户还要再一次进行用户认证 因为根据http协议 服务器并不知道是哪个用户发出的请求 所以 为了识
  • 易语言服务器客户端网络验证,超强网络验证系统附远程服务支持库

    这套网络验证我自己用了好几年 也是在几年前开发的 并且完整开源的源码 如果真 超级列表框 取表项数 0 信息框 先读取要导出的充值卡信息 48 提示 返回 如果真结束 如果真 信息框 是否要导出选列表框中 到文本 超级列表框 取表项数 条数
  • openwrt运行linux软件,OpenWrt运行go程序(交叉编译)-Go语言中文社区

    OpenWrt运行go程序 交叉编译 引言 因项目要求 需要在openwrt系统上运行http服务 由于对openwrt自带的uhttpd服务器及luci不熟悉 所以决定采用go语言来实现http服务 以下是配置go的过程以及踩过的一些坑
  • 【AI人工智能】 iTab浏览器标签页中最强大的AI功能莫过于此了, 你不用真的太可惜了! 最后一步就这样干(3)

    个人主页 极客小俊 作者简介 web开发者 设计师 技术分享博主 希望大家多多支持一下 我们一起进步 如果文章对你有帮助的话 欢迎评论 点赞 收藏 加关注 集成使用AI功能 接着我们打开Chrome浏览器 你就会发现标签页变成了iTab专属
  • Koa-router异步返回ctx.body失效的问题

    情景复现 router put category id ctx next gt const data ctx request body db updateCategoryById ctx params id data then doc gt
  • var' used instead of 'let' or 'const' 解决方案

    点击右下角的Apply 就可以啦
  • Unity2019.3API教程(三)GameObject类

    GameObject类 1 官方定义 class in UnityEngine Inherits from Object Implemented in UnityEngine CoreModule 属于 UnityEngine命名空间下的类