【Unity】C#脚本编写 [基础]
1.物体操作
public class EmptyTest : MonoBehaviour
{
//对应子组件,通过拖拽进行关联
public GameObject cube;
//获取预设体(unity编辑器里,拖拽关联)
public GameObject Prefab;
// Start is called before the first frame update
void Start()
{
//物体名
Debug.Log(gameObject.name);
//物体标签
Debug.Log(gameObject.tag);
//物体图层
Debug.Log(gameObject.layer);
//画线
Debug.DrawLine(new Vector3(1, 0, 0), new Vector3(1, 1, 0), Color.red);
//是否真正激活(也许会跟着父物体一起)
Debug.Log(cube.activeInHierarchy);
//自身激活
Debug.Log(cube.activeSelf);
//获取Transform组件
Debug.Log(transform.position);
//获取其他组件
BoxCollider bc = GetComponent<BoxCollider>();
//获取当前物体子物体身上的某个组件
GetComponentInChildren<CapsuleCollider>(bc);
//获取当前物体父物体身上的某个组件
GetComponentInParent<BoxCollider>(bc);
//添加一个组件
cube.AddComponent<AudioSource>();
//通过游戏物体的名称来获取游戏物体
GameObject test = GameObject.Find("test");
//通过游戏标签来获取游戏物体
test = GameObject.FindWithTag("test");
//通过预设体实例化游戏物体
Instantiate(Prefab);
//通过预设体实例化游戏物体 并 作为当前物体的子物体存在
Instantiate(Prefab,transform);
//通过预设体实例化游戏物体 并 放置到指定的位置
Instantiate(Prefab, Vector3.zero,Quaternion.identity);
//销毁
Destroy(test);
}
// Update is called once per frame
void Update()
{
}
}
2.时间操作
public class TimeTest : MonoBehaviour
{
float timer = 0;
// 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
void Update()
{
//计时器,脚本开始执行到现在过了多久
timer = timer + Time.deltaTime;
Debug.Log(timer);
//上一帧到这一帧所用的游戏时间
Debug.Log(Time.deltaTime);
}
}
3.文件操作
public class ApplicationTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//游戏数据文件夹路径(/Assets) 只读,加密压缩
Debug.Log(Application.dataPath);
//持久化文件夹路径 (不同平台下的保存文件的地址)
Debug.Log(Application.persistentDataPath);
//StreamingAssets文件夹 (只读,但不会加密压缩)(需要自己创建文件夹)
Debug.Log(Application.streamingAssetsPath);
//临时文件夹
Debug.Log(Application.temporaryCachePath);
//是否后台运行
Debug.Log(Application.runInBackground);
//打开Url
Application.OpenURL("www.baidu.com");
//退出游戏
Application.Quit();
}
// Update is called once per frame
void Update()
{
}
}
4.场景管理
public class SceneTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//场景类
//通过索引加载场景
SceneManager.LoadScene(1);
//通过名称加载场景
SceneManager.LoadScene("myScene");
//获取当前场景
Scene scene = SceneManager.GetActiveScene();
//场景名称
Debug.Log(scene.name);
//场景是否被加载
Debug.Log(scene.isLoaded);
//场景路径
Debug.Log(scene.path);
//场景索引
Debug.Log(scene.buildIndex);
//获取场景中的物体
GameObject[] gos = scene.GetRootGameObjects();
//场景管理类
//当前活动的场景数量
Debug.Log(SceneManager.sceneCount);
//创建新场景
Scene newScene = SceneManager.CreateScene("newScene");
//卸载场景
SceneManager.UnloadSceneAsync(newScene);
//加载场景(叠加到现有的)
SceneManager.LoadScene("myScene",LoadSceneMode.Additive);
//加载场景 (异步加载)
}
// Update is called once per frame
void Update()
{
}
}
5.异步加载场景,获取加载进度
public class AsyncTest : MonoBehaviour
{
//加载返回
AsyncOperation operation;
// Start is called before the first frame update
void Start()
{
StartCoroutine(loadScene());
}
//异步加载场景
IEnumerator loadScene()
{
operation = SceneManager.LoadSceneAsync(1);
//加载完场景不自动跳转
operation.allowSceneActivation = false;
yield return operation;
}
float timer = 0;
// Update is called once per frame
void Update()
{
//加载进度 ( 0 - 0.9)
Debug.Log(operation.progress);
//一段时间后跳转
timer = timer + Time.deltaTime;
if (timer > 5) {
//等待5秒后自动跳转场景
operation.allowSceneActivation = true;
}
}
}
6.Transform
public class TransformTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//获取位置
//世界位置
Debug.Log(transform.position);
//相对位置(父
Debug.Log(transform.localPosition);
//获取旋转
Debug.Log(transform.rotation);
Debug.Log(transform.localRotation);
//欧拉角
Debug.Log(transform.eulerAngles);
Debug.Log(transform.localEulerAngles);
//获取缩放
Debug.Log(transform.localScale);
//向量
//前,右,上
Debug.Log(transform.forward);
Debug.Log(transform.right);
Debug.Log(transform.up);
//父子关系
GameObject parent = transform.parent.gameObject;
//子物体个数
Debug.Log(transform.childCount);
//解除与子物体的父子关系
transform.DetachChildren();
//获取子物体
Transform child1 = transform.Find("Child1");
child1 = transform.GetChild(0);
//判断一个物体是不是另一个物体的子物体
bool res = transform.IsChildOf(child1);
Debug.Log(res);
//设置父物体
child1.SetParent(transform);
}
// Update is called once per frame
void Update()
{
//时刻看向 0,0,0
transform.LookAt(Vector3.zero);
//旋转
transform.Rotate(Vector3.up,1);
//绕某个物体旋转(绕的点,绕的轴,帧旋转值)
transform.RotateAround(Vector3.zero, Vector3.up, 5);
//移动(向前0.1/帧)
transform.Translate(Vector3.forward * 0.1f);
}
}
7.键鼠操作
public class KeyTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//鼠标的点击
//单击按下鼠标 0左键,1右键,2滚轮
if (Input.GetMouseButtonDown(0)) {
Debug.Log("鼠标左键按下了");
}
//持续按下鼠标
if (Input.GetMouseButton(0))
{
Debug.Log("鼠标持续按着");
}
//抬起鼠标按键
if (Input.GetMouseButtonUp(0))
{
Debug.Log("鼠标按键抬起");
}
//键盘按键
//按下键盘按键
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("按下了A");
}
//持续按下键盘按键
if (Input.GetKey(KeyCode.A))
{
Debug.Log("A持续按下");
}
//按键抬起(可以使用字符'a')
if (Input.GetKeyUp(KeyCode.A))
{
Debug.Log("A抬起");
}
}
}
8.虚拟轴操作
public class AxisTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//获取水平轴
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
//虚拟按键
if (Input.GetButtonDown("jump")) {
Debug.Log("空格");
}
if (Input.GetButton("jump"))
{
Debug.Log("空格");
}
if (Input.GetButtonUp("jump"))
{
Debug.Log("空格");
}
}
}
9.触屏/触摸 (Touch)
public class TouchTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//开启多点触摸
Input.multiTouchEnabled = true;
}
// Update is called once per frame
void Update()
{
//单点触摸
if (Input.touchCount == 1) {
//触摸对象
Touch touch = Input.touches[0];
//触摸位置
Debug.Log(touch.position);
//触摸阶段
switch (touch.phase) {
//开始
case TouchPhase.Began:
break;
//移动
case TouchPhase.Moved:
break;
//静止
case TouchPhase.Stationary:
break;
//打断
case TouchPhase.Ended:
break;
//结束
case TouchPhase.Canceled:
break;
}
}
//多点触摸
if (Input.touchCount == 2) {
//多个触摸的位置
Touch touch1 = Input.touches[0];
Touch touch2 = Input.touches[1];
}
}
}
10.移动控制
public class MoveTest : MonoBehaviour
{
//获取组件
private CharacterController player;
// Start is called before the first frame update
void Start()
{
player = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//水平轴
float horizontal = Input.GetAxis("Horizontal");
//垂直轴
float vertical = Input.GetAxis("Vertical");
//创建为一个方向向量
Vector3 dir = new Vector3(horizontal,0,vertical);
player.SimpleMove(dir * 3);
}
}
11.碰撞检测
(两个物体发生碰撞,前提必须有一个物体是刚体)
//发生碰撞
//Collision 碰撞到的物体的信息
private void OnCollisionEnter(Collision collision)
{
//获取碰撞到的物体
Debug.Log(collision.gameObject.name);
}
//持续碰撞中
private void OnCollisionStay(Collision collision)
{
}
//结束碰撞
private void OnCollisionExit(Collision collision)
{
}
12.触发器
//触发器
//Collider 进入触发的碰撞器
private void OnTriggerEnter(Collider other)
{
}
private void OnTriggerStay(Collider other)
{
}
private void OnTriggerExit(Collider other)
{
}
13.使用刚体控制移动
public class playerMove : MonoBehaviour
{
//刚体实例
private Rigidbody player;
//动画控制器实例
private Animator animator;
//虚拟轴
private float horizontal;
private float vertical;
//移动向量
Vector3 movement;
//用四元数表示旋转
//初始化表示不旋转
Quaternion Rotation = Quaternion.identity;
//旋转速递
public float turnSpeed = 20.0f;
// Start is called before the first frame update
void Start()
{
player = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//水平轴
horizontal = Input.GetAxis("Horizontal");
//垂直轴
vertical = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
//初始化移动向量
movement.Set(horizontal, 0, vertical);
movement.Normalize();
//判断是否有横向移动/纵向移动
bool hasHorizontal = !Mathf.Approximately(horizontal, 0.0f);
bool hasVertical = !Mathf.Approximately(vertical, 0.0f);
//判断是否在移动
bool isRunning = hasHorizontal || hasVertical;
animator.SetBool("isRun", isRunning);
//用三维矢量来表示转向后玩家的方向
Vector3 desiredForward = Vector3.RotateTowards(transform.forward,movement,turnSpeed * Time.deltaTime,0f);
Rotation = Quaternion.LookRotation(desiredForward);
}
private void OnAnimatorMove()
{
//使用用户输入的三维矢量作为移动方向,使用动画中每次0.02秒移动距离作为距离
player.MovePosition(player.position + movement * 0.05f);
player.MoveRotation(Rotation);
}
}