代码获取组件
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;// 必须要继承 MonoBehaviour 才是一个组件
// 类名必要与文件名一致public class c1 : MonoBehaviour
{// 使用 public 初始变量时,使用命名用英语,Unity界面会将该变量翻译为中文并且可以随时调整数值// public float num = 1;// 关联预设体(将预制体拖动到脚本的 "预制体" 上, 通过代码实例化预制体)public GameObject prefab; // prefab-预制体// Start在第一帧更新之前被调用void Start(){Debug.Log("Start 被调用了");// 获取脚本挂载的游戏物体GameObject go = this.gameObject;// 打印游戏物体名称Debug.Log(go.name);// 标签Debug.Log(go.tag);// 层Debug.Log(go.layer);// 获取激活状态// 真实激活状态Debug.Log(go.activeInHierarchy);// 自己组件的激活状态Debug.Log(go.activeSelf);// 设置激活状态// go.SetActive(true);// 获取组件// 1.获取Transform组件Transform trans = this.transform;// 2.获取其他组件 (碰撞组件-Collider)Collider collider = this.GetComponent<Collider>();// Debug.Log(collider);// 3.获取父物体组件 (碰撞组件-BoxCollider)BoxCollider bc = this.GetComponentInParent<BoxCollider>();// Debug.Log(bc);// 4.获取子物体组件 ()CapsuleCollider cc = this.GetComponentInChildren<CapsuleCollider>();Debug.Log(cc.name);// 动态添加组件 (声音组件-AudioSource)// this.AddComponent<AudioSource>();// 通过物体名称找到物体 (物体名称-Cube)GameObject cube = GameObject.Find("Cube");// Debug.Log(cube.name);// 修改物体名称// cube.name = "123";// 通过标签找到物体 (标签名称-p1)添加新标签p1// GameObject cube2 = GameObject.FindWithTag("p1");// cube2.name = "new cube2";// 通过标签找到物体 (返回数组)// GameObject[] cube2 = GameObject.FindGameObjectsWithTag("p1");// Debug.Log(cube2);// 实例化预制体(需要先关联预制体)// GameObject S1 = Instantiate(prefab, Vector3.zero, Quaternion.identity);}// 每帧调用一次Updatevoid Update(){// Debug.Log("Update 被调用了");}// 在 Update 后调用private void LateUpdate(){// Debug.Log("LateUpdate 被调用了");}
}
关联预制件,先选中物体,将预制件拖动到脚本的"预制件"上面。