当前位置:网站首页>Unity脚本API—GameObject游戏对象、Object 对象

Unity脚本API—GameObject游戏对象、Object 对象

2022-07-04 14:13:00 @夜魅

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// GameObject 游戏对象
/// </summary>
public class GameObjectDemo : MonoBehaviour
{
    private void OnGUI()
    {
        //在场景中物体激活状态(物体实际激活状态)
        //this.gameObject.activeInHierarchy;

        //物体自身激活状态(物体在Inspector面板中的状态)
        //this.gameObject.activeSelf

        //设置物体启用/禁用
        //this.gameObject.SetActive();

        if (GUILayout.Button("添加光源")) 
        {
            //this.gameObject.AddComponent<Light>();
            //创建物体
            GameObject lightGO= new GameObject();
            //添加组件
            Light light = lightGO.AddComponent<Light>();    
            light.color = Color.red;
            light.type = LightType.Point;
        }

        //在场景中根据名称查找物体(慎用)
        //GameObject.Find("游戏对象名称");

        //获取所有使用该标签的物体
        GameObject[] allEnemy = GameObject.FindGameObjectsWithTag("Enemy");
        foreach (GameObject enemy in allEnemy)
        {
            Debug.Log("Enemy"+enemy.name);
        }
          
        //获取使用该标签的物体(单个)
        GameObject playerGo = GameObject.FindWithTag("Player");
        Debug.Log("Player"+playerGo.name);

        //Object

        //根据类型查找对象
        Object.FindObjectOfType<MeshRenderer>();
        FindObjectsOfType<MeshRenderer>();

        //销毁对象
        //Object.Destroy

        //练习:查找血量最低的敌人
    }

}

原网站

版权声明
本文为[@夜魅]所创,转载请带上原文链接,感谢
https://blog.csdn.net/LOVE_Me__/article/details/125463043