常用的调试
Debug.Log(); 普通消息日志
Debug.LogWarning(); 警告日志
Debug.LogError(); 错误日志
Debug.DrawLine(); 绘制线
Debug.DrawRay(); 绘制射线
物体类的使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EmptyTest : MonoBehaviour
{
public GameObject Cube; //被声明为public的变量会显示到物体的组件 可选择物体进行绑定
public GameObject Prefab; //获取预设体
// Start is called before the first frame update
void Start()
{
//拿到当前脚本所挂载的游戏物体
GameObject go = this.gameObject; //this可省略
Debug.Log(go.name); //名称
Debug.Log(gameObject.tag); //标签
Debug.Log(gameObject.layer); //图层 索引
Debug.Log(Cube.name); // 立方体的名称
// 立方体的激活状态 当前物体的真正的激活状态,如果它是一个非激活物体的子物体那么结果总是false
Debug.Log(Cube.activeInHierarchy);
// 立方体的激活状态 当前自身激活状态,如果它是一个非激活物体的子物体那么结果还是它自身的激活状态
Debug.Log(Cube.activeSelf);
// 获取Transform组件
Transform t = this.transform; // 也可直接使用transform
// 获取其他组件
BoxCollider bc = GetComponent<BoxCollider>(); //可直接用GetComponent<需要获取组件的泛型>()方法来获取该游戏物体的某个组件
// 获取当前物体的子物体身上的某个组件
GetComponentInChildren<Transform>();
// 获取当前物体的父物体身上的某个组件
GetComponentInParent<CapsuleCollider>();
// 添加一个组件
gameObject.AddComponent<AudioSource>();
Cube.AddComponent<BoxCollider>();
// 通过游戏物体的名称获取游戏物体
GameObject testCube = GameObject.Find("TestCube");
// 通过游戏标签获取游戏物体
testCube = GameObject.FindWithTag("player");
testCube.SetActive(false); // 设置激活状态
// 通过预设体实例化游戏物体 向场景中添加一个预设题的游戏物体
Instantiate(Prefab);
Instantiate(Prefab, transform); //在当前物体的子物体中实例化一个预设体物体
Instantiate(Prefab, Vector3.zero, Quaternion.identity); //添加到0,0位置 不旋转
// 销毁物体
Destroy(Cube);
}
// Update is called once per frame
void Update()
{
}
}
游戏时间的使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimeTest : MonoBehaviour
{
float timer = 0;
int intTimer = 0; // timer的整数位
// Start is called before the first frame update
void Start()
{
//游戏开始到现在所花的时间
Debug.Log(Time.time);
//时间缩放值
Debug.Log(Time.timeScale);
//固定时间间隔
Debug.Log(Time.fixedDeltaTime);
}
// Update is called once per frame
// 如果电脑帧数是60 时间就是1/60
void Update()
{
//上一帧到这一帧所用的游戏时间
//Debug.Log(Time.deltaTime);
timer += Time.deltaTime; //可作为游戏计时器 游戏脚本运行时间
if (intTimer == (int)timer)
{
Debug.Log(intTimer); //此时就实现了计时器每秒打印一次的效果
intTimer++;
}
}
}