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.
using UnityEngine;publicclassNewBehaviourScript:MonoBehaviour{voidStart(){GameObject go =newGameObject();
go.AddComponent(typeof(Rigidbody));Rigidbody rg = go.GetComponent(typeof(Rigidbody))as Rigidbody;
rg.gameObject.AddComponent(typeof(Mesh));}}