获取对象/组件

获取对象/组件(Unity)

Unity 开发中获取对象和组件是最基础的操作。

获取 GameObject

// 自身
gameObject
this.gameObject

// 通过名称(场景中查找,性能较低)
GameObject.Find("Enemy");
GameObject.FindWithTag("Player");

// 实例化
Instantiate(prefab);
Instantiate(prefab, position, rotation);

// 通过父子关系
transform.parent.gameObject;
transform.Find("Child/SubChild").gameObject;

获取组件(Component)

// 自身组件
GetComponent<Rigidbody>();
GetComponentInChildren<Renderer>();   // 子物体
GetComponentInParent<Collider>();     // 父物体

// 给其他对象加组件/取组件
otherGameObject.GetComponent<ScriptName>();
otherGameObject.AddComponent<ScriptName>();

// 查找多个
GetComponents<Collider>();           // 数组

常用单例模式

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }
    void Awake() => Instance = this;
}

“您的支持是我持续分享的动力”

微信收款码
微信
支付宝收款码
支付宝

目录