Unity2019.3API教程(四)Component类

Component类

1. 官方定义
class in UnityEngine/Inherits from:Object/Implemented in:UnityEngine.CoreModule
属于UnityEngine命名空间下,继承自Object类,与之前的Object类和GameObject类一样属于核心模块。

2. 官方描述
Base class for everything attached to GameObjects.
Note that your code will never directly create a Component. Instead, you write script code, and attach the script to a GameObject. See Also: ScriptableObject as a way to create scripts that do not attach to any GameObject.
此类要对比下GameObject类,GameObject类是场景中所有实体的基类,而Component类是挂载在实体身上所有组件的基类,官方强调脚本是一个组件,但是脚本不可以直接挂载到实体上,当然官方介绍的ScriptableObject类是一种不附加到实体上的方法,后续再做介绍。

3. 属性
gameObject:The game object this component is attached to. A component is always attached to a gameobject.
语法:public GameObject gameObject;
获取自身物体,Component类比较特殊,除了gameobject这个属性,其他的与GameObject类的属性和方法相同,我这边全部裂解液出来,再在最后说明原因。

tag:The tag of this game object.

transform:The Transform attached to this GameObject.

4. 共有方法
BroadcastMessage:Calls the method named methodName on every MonoBehaviour in this game object or any of its children.

CompareTag:Is this game object tagged with tag ?

GetComponent:Returns the component of Type type if the game object has one attached, null if it doesn’t.

GetComponentInChildren:Returns the component of Type type in the GameObject or any of its children using depth first search.

GetComponentInParent:Returns the component of Type type in the GameObject or any of its parents.

GetComponents:Returns all components of Type type in the GameObject.

GetComponentsInChildren:Returns all components of Type type in the GameObject or any of its children.

GetComponentsInParent:Returns all components of Type type in the GameObject or any of its parents.

SendMessage:Calls the method named methodName on every MonoBehaviour in this game object.

SendMessageUpwards:Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.

TryGetComponent:Gets the component of the specified type, if it exists.

以上就是官方2019.3版本Component类的全部内容,看过第三期教程的朋友会发现属性和方法和GameObject类基本相同,这是为什么呢,因为Unity在设计时,通过GameObject类创建场景实体,而实体的属性和功能通过组件来完成,而组件时挂载在实体上的,所以Component类给出gameobject属性(注意此处为小写),gameobject时Component类的属性,很多朋友在学习API时对于Object,GameObject以及gameobject发生混淆,Object和GameObject时类,具有父子关系,他们同属于UnityEngine命名空间下,而gameobject属于Component类的一个属性,Component类和Object也是一种父子关系,Component类和GameObject类在设计上属于同级关系,但是基于Unity的设计,在实现上,GameObjec类是实现的基础,而Component类是实现的行为外观,这里还要提一个Object类,根据Unity结构,他不属于UnityEngine命名空间下,而是System.Object,属于最终基类,因为我们用UNity写的脚本现在都是C#语言,这里只做概述不做具体介绍。所以,我们可以通过组件访问挂载物体,从而实现访问,示例如下:

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    
    void Start()
    {
        GameObject go = new GameObject();
        go.AddComponent(typeof(Rigidbody));
        Rigidbody rg = go.GetComponent(typeof(Rigidbody))as Rigidbody;
        rg.gameObject.AddComponent(typeof(Mesh));
    }
}

后面官方给的是继承的内容,此处不做概述,本期教程到此结束,欢迎大家在评论区给出意见和指正,谢谢浏览。

你可能感兴趣的:(Unity,API,游戏开发,unity3d)