Unity2019.3API教程(三)GameObject类

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类,在之前已经讨论过,这里不在赘述。

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值