@[TOC]Unity常用类
三.Unity常用类(下)
6.Transform类
表示一个物体的位置旋转缩放,维系一个物体的父子关系
// 获取Transform组件 Transform t = GetComponent(); gameObject.transform transform 属性属性作用position物体的世界坐标(世界坐标)localPosition物体相对于父物体的坐标(物体坐标)eulerAngles欧拉角旋转(世界坐标)localEulerAngles欧拉角旋转(物体坐标)rotation四元数旋转(世界坐标)localRotation四元数旋转(物体坐标)localScale物体的缩放parent得到父物体的transformroot得到根物体的transformchildCount返回子物体的个数常量常量值forward物体自己的z轴正方向(前方)right物体自己的x轴正方向(右方)up物体自己的y轴正方向(上方)方法方法定义作用transform.Translate(Vector3 v3)只移动一次(物体坐标)transform.Translate(Vector3 v3, Space relativeTo)只移动一次(Space坐标)transform.Rotate(Vector3 axis, float angle)沿轴axis,旋转angle角度(自转)(物体坐标)transform.RotateAround(Vector3 point, Vector3 axis, float angle)绕着point,沿轴axis,旋转angle角度(公转)transform.LookAt(Transform transform)z轴正方向指向某个物体transform.SetParent(Transform transform)设置父物体transform.GetChild(int index)获得子物体(index是子物体的序号)transform.Find(string name)获得子物体(通过子物体的名字)transform.GetSiblingIndex()获取物体在父物体中的下标transform.SetSiblingIndex(int index)修改物体在父物体中的下标transform中所有的查找方法可以找到非激活的// 速度每秒10米 用10 * Time.deltaTime transform.Translate(Vector3.right * 10 * Time.deltaTime); // 沿物体坐标 transform.Translate(Vector3.right * 10 * Time.deltaTime, Space.World); // 沿世界坐标 // 获取主摄像机的Camera组件 // 主摄像机:具有MainCamera的tag值的物体 Camera c = Camera.main;
7.Quaternion 类
欧拉角转四元数Quaternion rotation = Quaternion.Euler(Vector3 euler); Quaternion rotation = Quaternion.Euler(float x, float y, float z); 四元数转欧拉角Vector3 euler = rotation.eulerAngles; 空旋转Quaternion.identity 插值函数Quaternion.Lerp(Quaternion a, Quaternion b, float t); 将一个向量转成一个四元数,用来取方向Quaternion.LookRotation(Vector3 forward); 向量右乘(Quaternion * Vector3)
几何含义:将向量旋转指定的四元数角度Vector3 result = Quaternion.Euler(0, 90, 0) * Vector3.forward; // result是 Vector3.right (1, 0, 0)
8.Input类
8.1 键盘、鼠标
检测按键一定不能写在FixedUpdate()中,检测是每一帧检测一次,FixedUpdate可能一帧触发多次获取鼠标在屏幕上的位置屏幕坐标是左下角为(0, 0, 0)点,右上角为(Screen.width, Screen.height, 0)点Screen.width屏幕宽Screen.height屏幕高Vector3 mousePosition = Input.mousePosition; 点击鼠标键盘// KeyCode是一个枚举,包含几乎所有按键 bool isPress = Input.GetKey(KeyCode key) // 按住按键持续触发 bool isUp = Input.GetKeyUp(KeyCode key) // 按键抬起的时候触发一次 bool isDown = Input.GetKeyDown(KeyCode key) // 按键按下的时候触发一次 bool isDown = Input.GetKeyDown(string name) // 容易写错,不推荐 // 专门检测鼠标按键的,用button数字代表按钮 Input.GetMouseButton(int button) Input.GetMouseButtonUp(int button) Input.GetMouseButtonDown(int button)
8.2 Input虚拟轴
Horizontal轴:水平Vertical轴:垂直Mouse X轴:鼠标在水平方向上的偏移量Mouse Y轴:鼠标在垂直方向上的偏移量Mouse ScrollWheel轴:鼠标滚轮的偏移量float horizontal = Input.GetAxis(“Horizontal”); float vertical = Input.GetAxis(“Vertical”); // 容错判断 if (Mathf.Abs() < 0.1f || Mathf.Abs() < 0.1f) return; // 做一个方向向量 Vector3 direction = new Vector3(horizontal, 0, vertical); if (direction != Vector3.zero) { // 得到目标方向 Quaternoin target = Quaternion.LookRotation(direction); // 旋转 transform.rotation = Quaternion.Lerp(tranform.rotation, target, Time.deltaTime * speed); // 移动 transform.translate(Vector3.forward * speed * Time.deltaTime); }
父物体想要放在子物体中心:
将父物体作为子物体的子物体reset transform再将子物体作为父物体的子物体
9.Application 类
都是静态的,用Application.xxxx
runInBackground:游戏是否支持后台运行dataPath:返回当前工程的Assets文件夹路径persistentDataPath:根据发布的平台,返回一个持久化路径streamingAssetsPath:返回一个StreamingAssets文件夹的路径,是Assets文件夹的一个子文件夹,打包后这个文件夹依然存在OpenURL:打开指定的网页Quit():关闭当前应用程序(只有打完包(发布应用程序)后才有效,手游几乎没有)
10.ScreenCapture 类
ScreenCapture.CaptureScreenshot(“绝对路径”):截图
使用代码截图using System; using System.IO; // 判断 bool exists = Directory.Exists(Application.persistentDataPath + “/Images”); if (exists == false) { // 创建文件夹 Directory.Cre
11.Scene Manager 类
场景切换:在发起切换的场景中做一个panel,做切换画面,放一个Slider把Handler删除,Interactable取消勾选,动态修改value值为asyncOperation.progressusing UnityEngine.SceneManagement; // 1. 将需要切换的场景添加到Scenes In Build // File -> Build Settings -> Scenes In Build // 按按钮添加,右键选场景删除 // 拖拽后每一个场景都有一个编号 // 2. 使用SceneManager类来切换 // 同步切换 void SceneManager.LoadScene(string name); // 通过场景名字切换 void SceneManager.LoadScene(int index); // 通过场景下标编号切换 // 异步切换 AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(string name); // 通过场景名字切换 AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(int index); // 通过场景下标编号切换 // 可以通过asyncOperation拿到切换的进度 // 在Update()中使用进度 private void Update() { if (asyncOperation != null) { print(asyncOperation.progress); } } DontDestroyOnLoad 静态方法
此静态方法允许游戏物体在加载任何场景的时候不销毁,只能让根物体不销毁,可以用来管理全局的事务DontDestroyOnLoad(Object target);
使用此方法存在一个问题,当在A场景生成了DontDestroyOnLoad的游戏物体后,切换B场景,再切回A场景,会出现多次调用该方法,从而无限循环,解决办法如下:
将需要全局保留的物体放到一个初始场景里,游戏运行第一时间就加载,加载完成再跳到初始页面判断该方法是否已经调用过,设一个全局(静态)变量默认False,当运行过一次之后将其变为True,之后每次进入判断True是否调用使用静态构造方法,当第一次使用这个类的时候调一次,所以这个静态构造方法全局只会调用一次,在这个构造方法中创建空物体,将此脚本绑定上去,再DontDestroyOnLoad这个空物体,此时这个DontDestroyOnLoad全局只会调用一次,这个脚本也做成了类似单例脚本,使用方便
12.Audio Source 类
用于管理播放声音文件
AudioSource组件AudioClip:音源文件Output:混音调音Mute:静音Loop:循环Volume:音量Spatial Blend:使用2D还是3D声音。2D声音没有位置;3D声音有位置,可以调声音曲线// 获得AudioSource组件 private AudioSource _audio; _audio = GetComponent(); // 加载播放音效 AudioClip clip = Resources.Load(string path); // 播放一次 _audio.PlayOneShot(clip); // 设置一个新的要播放的声音片段 _audio.clip = clip; // 设置其他的 _audio.loop = loop; // 背景音播放 _audio.Play(); // 死亡第一段 private void Die1() { // 延迟播放第二段 Invoke(“Die2”, 0.5f); } // 死亡第二段 private void Die2() { }
13.Invoke 延迟调用
Invoke(string functionName, float delay); 延迟调用方法CancelInvoke(string functionName); 取消指定方法的延迟调用Cancel(); 取消所有延迟调用的方法
14.Gizmos 类
Gizmos是用于在场景视图可视化调试或辅助设置所有gizmo绘制需要在脚本的OnDrawGizmos或OnDrawGizmosSelected里完成OnDrawGizmos在每帧调用。所有在OnDrawGizmos中渲染的gizmos都是可见的。OnDrawGizmosSelected仅在脚本附加的物体被选择时被调用。静态变量变量名作用Gizmos.color为随后绘制的gizmos设置颜色Gizmos.matrix设置gizmo的矩阵用于绘制所有gizmos静态方法方法名作用Gizmos.DrawCube(Vector3 center, Vector3 size)绘制立方体,使用center和size参数,绘制一个实心立方体Gizmos.DrawFrustum(Vector3 center, float fov, float maxRange, float minRange, float aspect)绘制相机可视区域,用当前的Gizmos.matrix设置它的位置和旋转,参数:center(棱锥体的顶点),fov(视角大小,角度制),maxRange(视野最大距离),minRange(视野最小距离),aspect(宽高比,宽/高)Gizmos.DrawIcon(Vector3 center, string name, bool allowScaling = true)绘制图标,图标被命名为name并且被放置在center处。图标的路径需要放在Assets/Gizmos文件夹Gizmos.DrawLine(Vector3 from, Vector3 to)绘制线段,绘制一条从from起点到to位置的线段Gizmos.DrawRay(Ray ray)绘制射线Gizmos.DrawRay(Vector3 from, Vector3 direction)绘制射线,从from开始向direction绘制一条射线Gizmos.DrawSphere(Vector3 center, float radius)绘制球体,使用center和radius参数,绘制一个实心球体Gizmos.DrawMesh(Mesh mesh, Vector3 position = Vector3.zero, Quaternion rotation = Quaternion.identity, Vector3 scale = Vector3.one)绘制一个网格Gizmos.DrawWireCube(Vector3 center, Vector3 size)绘制线框立方体,使用center和size参数,绘制一个线框立方体Gizmos.DrawWireSphere(Vector3 center, float radius)绘制线框球体,根据center和radius参数设置线框球体