Unity is a tool for creating and growing games, apps, and experiences across 20+ platforms and devices. Learn how to use Unity’s end-to-end solutions, services, and community resource
1.C#脚本
脚本的基本结构,其中Move是脚本名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 using System.Collections;using System.Collections.Generic;using UnityEngine;public class Move : MonoBehaviour { void Start () { } void Update () { } }
脚本的生命周期
Awake 最早调用
当物体载入时立即调用1次;常用于在游戏开始前进行初始化,可以判断当前满足某种条件执行此脚本,this.enable = true;
OnEnable 激活后,只会调用一次
Start 调用一次,可以设置初始值
FixedUpdate 固定频率调用
Update 每帧调用一次
LateUpdate 在Update之后调用
OnDisable 组件未激活调用
OnDestroy 销毁
OnApplicationQuit()当前程序结束时
[SerializeField] 在编辑器中无法修改,在脚本内可修改
序列化字段
1 2 [SerializeField ] private int a = 100 ;
[HideInInspector]在编辑器中无法显示
1 2 [HideInInspector ] private int b;
[Range()]
1 2 [Range(0,100) ] private int c;
2.脚本的执行顺序
先执行所有脚本的Awake方法,再执行所有脚本的OnEnable方法。。。
在Execution Order可以更改脚本的执行顺序
3.标识
Tag 唯一标识符
Layer 图层,用于碰撞检测
4.预制体和变体 1.预制体
rigidbody 添加重力
多个物体有相同的预设可以使用预设体
2.变体
原本的预设体会影响变体,变体的预设体只会影响变体
5.Vector3的使用
向量、坐标、旋转,缩放
1 2 Vector3 v = new Vector3(); Vector3 v3 = new Vector3(1 , 0.5f ,0.6f );
1 2 v3 = Vector3.zero; v3 = Vector3.one;
修改向量的xyz值
两个向量的计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Debug.Log(Vector3.Angle(v31, v3)); Debug.Log(Vector3.Distance(v31, v3)); Debug.Log(Vector3.Dot(v31, v3)); Debug.Log(Vector3.Cross(v31, v3)); Debug.Log(Vector3.Lerp(Vector3.zero, Vector3.one, 0.5f )); Debug.Log(v3.magnitude); Debug.Log(v3.normalized);
6.欧拉角与四元数 1 2 3 4 5 6 7 8 9 Vector3 rotate = new Vector3(0 ,30 ,0 ); Quaternion quat = Quaternion.identity; quat = Quaternion.Euler(rotate); rotate = quat.eulerAngles ; quat = Quaternion.LookRotation(new Vector3(0 ,0 ,0 ));
7.Debug
可以定义共有变量,程序运行后再检测面板查看数据
1 2 3 4 5 6 7 8 9 10 Debug.Log("" ); Debug.LogWarning("" ); Debug.LogError("" ); Debug.DrawLine(Vector3.one, Vector3.zero, Color.red); Debug.DrawRay(Vector3.one, Vector3.up, Color.yellow);
8.游戏物体的使用方法
拿到当前脚本所挂载的游戏物体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class EmptyTest : MonoBehaviour { public GameObject cube; void Start () { } void Update () { } }
判断组件的激活状态
1 2 3 4 Debug.Log(gameObject.activeInHierarchy); Debug.Log(gameObject.activeSelf);
获取transform组件
1 Transform trans = this .transform;
获取物体的组件
1 2 3 4 5 6 7 8 9 BoxCollider bc = GetComponent<BoxCollider>(); GetComponentInChildren<BoxCollider>(bc); GetComponentInParent<BoxCollider>(bc); cube.AddComponent<AudioSource>();
获取游戏物体
1 2 3 4 5 6 GameObject Capsule1 = GameObject.Find("Capsule" ); Debug.Log(Capsule1.name); GameObject Capsule2 = GameObject.FindWithTag("Player" ); Debug.Log(Capsule2.name);
Capsule1.SetActive(false);
取消激活
预设体
1 2 3 4 Instantiate(Prefab); Instantiate(Prefab,transform);
1 2 3 4 GameObject go = Instantiate(Prefab,Vector3.up,Quaternion.identity); Destroy(go);
9.游戏时间 1 2 3 4 5 6 7 8 Debug.Log(Time.time); Debug.Log(Time.timeScale); Debug.Log(Time.fixedDeltaTime); Debug.Log(Time.deltaTime);
10.路径权限 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Debug.Log(Application.dataPath + "/新建.txtx" ); Debug.Log(Application.persistentDataPath); Debug.Log(Application.streamingAssetsPath); Debug.Log(Application.temporaryCachePath); Debug.Log(Application.runInBackground); Application.OpenURL("https://www.baidu.com" ); Application.Quit();
11.场景类
场景类,场景管理类
1 2 3 4 5 6 SceneManager.LoadScene(1 ); SceneManager.LoadScene("Test" ); Scene scence = SceneManager.GetActiveScene(); Debug.Log(scence.name);
场景的API
1 2 3 4 5 6 7 8 9 10 Debug.Log(scence.isLoaded); Debug.Log(scence.path); Debug.Log(scence.buildIndex); GameObject[] games = scence.GetRootGameObjects(); Debug.Log(games.Length);
场景管理类
1 2 3 4 5 6 7 8 9 10 Debug.Log(SceneManager.sceneCount.ToString()); SceneManager.CreateScene("newScene" ); Debug.Log(SceneManager.sceneCount.ToString()); Scene newScene = SceneManager.CreateScene("newScene" ); SceneManager.UnloadSceneAsync(newScene);
加载场景
1 2 SceneManager.LoadScene("myscene" , LoadSceneMode.Single);
12.异步加载场景并获取进度 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class AsyncTest : MonoBehaviour { AsyncOperation operation; void Start () { StartCoroutine(loadScene()); } IEnumerator loadScene () { operation = SceneManager.LoadSceneAsync(1 ); yield return operation; } void Update () { } }
输出加载进度
1 2 Debug.Log(operation.progress.ToString());
模拟定时器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public class AsyncTest : MonoBehaviour { AsyncOperation operation; void Start () { StartCoroutine(loadScene()); } IEnumerator loadScene () { operation = SceneManager.LoadSceneAsync(1 ); operation.allowSceneActivation = false ; yield return operation; } float Timer = 0 ; void Update () { Debug.Log(operation.progress.ToString()); Timer += Time.deltaTime; if (Timer > 5 ) { operation.allowSceneActivation = true ; } } }
tranform API
1 2 3 4 5 6 7 8 9 10 11 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);
获取向量
1 2 3 4 5 6 Debug.Log(transform.forward); Debug.Log(transform.right); Debug.Log(transform.up);
1 2 3 4 5 6 7 8 9 10 11 transform.LookAt(new Vector3(0 , 0 , 0 )); transform.Rotate(Vector3.up, 1 ); transform.RotateAround(Vector3.zero,Vector3.up, 5 ); transform.Translate(Vector3.forward * 0.1f );
父子关系
1 2 3 4 5 6 transform.DetachChildren();
1 2 3 4 5 6 7 Transform trans = transform.Find("Children" ); transform.GetChild(0 ); bool res = trans.IsChildOf(transform);trans.SetParent(transform);
14.游戏操作方式
在update里面写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 if (Input.GetMouseButtonDown(0 )){ Debug.Log("" ); } if (Input.GetMouseButtonUp(0 )){ Debug.Log("" ); } if (Input.GetMouseButton(0 )){ Debug.Log("" ); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 if (Input.GetMouseButton(0 )){ Debug.Log("" ); } if (Input.GetKey(KeyCode.Space)){ Debug.Log("" ); } if (Input.GetKeyUp(KeyCode.Space)){ Debug.Log("" ); } if (Input.GetKeyDown(KeyCode.Space)){ Debug.Log("" ); }
15.操作兼容与过渡
Edit –> ProjectSetting –> input Manager –> axes
水平 Horizontal
垂直 Vertical
1 2 3 4 5 6 float horizontal = Input.GetAxis("Horizontal" );float vertical = Input.GetAxis("Vertical" );Debug.Log(horizontal + " " + vertical);
虚拟按键的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 if (Input.GetButtonDown("Jump" )){ Debug.Log("" ); } if (Input.GetButtonUp("Jump" )){ Debug.Log("" ); } if (Input.GetButton("Jump" )){ Debug.Log("" ); }
16.手机平板触屏 1 2 Input.multiTouchEnabled = true ;
判断单点触摸
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 ; } }
17.灯光与烘焙
定向灯光 –> 从无穷远的地方照射而来09
烘焙光 静态光
实时光 动态光会实时计算光的渲染
18.摄像机
摄像机深度越大,优先级越高
19.音频
添加Audio Source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public AudioClip music;public AudioClip se;public AudioSource player;void Start (){ player = GetComponent<AudioSource>(); player.clip = music; player.loop = true ; player.volume = 0.5f ; player.Play(); } void Update (){ if (Input.GetKeyDown(KeyCode.Escape)) { if (player.isPlaying) { player.Pause(); } else { player.UnPause(); } } }
1 2 player.PlayOneShot(se);
20.视频播放
Video Player
1 2 3 4 5 6 using UnityEngine.Video; private VideoPlayer mPlayer; void Start () { mPlayer = GetComponent<VideoPlayer>(); }
21.角色控制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class PlayerControll : MonoBehaviour { private CharacterController characterController; void Start () { characterController = GetComponent<CharacterController>(); } void Update () { float horizontal = Input.GetAxis("Horizontal" ); float vertical = Input.GetAxis("Vertical" ); Vector3 dir = new Vector3(horizontal,0 ,vertical); characterController.SimpleMove(dir); } }
22.物理系统
碰撞的产生与监听
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class PlayerControll : MonoBehaviour { private GameObject Prefab; void Start () { } void Update () { } private void OnCollisionEnter (Collision collision ) { Instantiate(Prefab,transform.position,Quaternion.identity); Destroy(gameObject); } private void OnCollisionStay (Collision collision ) { } private void OnCollisionExit (Collision collision ) { } }
触发
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 private void OnTriggerEnter (Collider other ){ GameObject go = GameObject.Find("Cube" ); if (go != null ) { go.SetActive(false ); } } private void OnTriggerStay (Collider other ){ } private void OnTriggerExit (Collider other ){ }
弹簧 Spring Joint
铰链
23.冰面与地面
物理材质的使用
静态摩擦和动态摩擦的使用
24.射线检测 1 2 3 4 Ray ray = new Ray(Vector3.zero,Vector3.up); ray = Camera.main.ScreenPointToRay(Input.mousePosition);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 if (Input.GetMouseButtonDown(0 )){ Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; bool res = Physics.Raycast(ray, out hit); if (res) { Debug.Log(hit.point); transform.position = hit.point; } RaycastHit[] hits = Physics.RaycastAll(ray, 100 ); }
25.彩色尾条和拖尾
Line Render
1 2 3 4 5 6 7 LineRenderer lineRenderer = GetComponent<LineRenderer>(); lineRenderer.positionCount = 3 ; lineRenderer.SetPosition(0 , Vector3.zero); lineRenderer.SetPosition(0 , Vector3.one); lineRenderer.SetPosition(0 , Vector3.forward);
Trail Render
26.动画组件
animation 旧组件
1 2 3 4 5 6 7 void Update (){ if (Input.GetMouseButtonDown(0 )) { GetComponent<Animation>().Play("name" ); } }
animatior 新组件
新建动画器控制器
27.模型动作 1 2 3 4 5 if (Input.GetKeyDown(KeyCode.F)){ GetComponent<Animator>().SetTrigger("triggername" ); }
1 2 3 4 5 6 7 8 9 float horizontal = Input.GetAxis("Horizontal" );float vertical = Input.GetAxis("VErtical" );Vector3 dir = new Vector3 (horizontal,0 , vertical); if (dir != Vector3.zero){ transform.rotation = Quaternion.LookRotation(dir); transform.Translate (dir * 1.5f ); }
28.帧事件的使用 1 2 3 4 5 6 7 8 void test1 (){ Debug.Log("test1" ); } void test2 (){ Debug.Log("test2" ); }
在脚落地时打上帧事件,播放踩地的声音
29.混合动画
设置权重权重越高显示在前
Avatar Mask 相当于蒙版
30.反向动力学
反向运动学 (IK) 是一种设置动画的方法,它翻转链操纵的方向。
1 2 3 4 5 6 7 8 9 10 11 private void OnAnimatorIK (int layerIndex ){ animator.SetLookAtWeight(1 ); animator.SetLookAtPosition(target.position); animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1 ); animator.SetIKRotationWeight(AvatarIKGoal.LeftHand, 1 ); }
31.导航网格
新版使用NavMeshSurface组件来进行
Nav Mesh Agent 导航代理组件(用于角色)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 private NavMeshAgent agent;void Start (){ agent = GetComponent<NavMeshAgent>(); } void Update (){ if (Input.GetMouseButtonDown(0 )) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Vector3 point = hit.point; agent.SetDestination(point); } } }
在两点之间传送
创建两个物体,其中一个绑定Off Mesh Link再绑定起始点
32.锚点和轴心点
当四个锚点均在同一点时,用轴点(Pivot)到锚点的水平距离和垂直距离来定位
33.按钮
使用图片前转为精灵图
在脚本内使用画布内的组件新版加入TMPro命名空间
绑定事件先将脚本绑定到画布,然后再按钮的鼠标单击事件中绑定脚本的鼠标单击事件方法(Button Click)
34.下拉选项Dropdown 1 2 3 4 5 6 7 8 9 10 void Start (){ Dropdown dropdown = GetComponent<Dropdown>(); List<Dropdown.OptionData> options = dropdown.options; options.Add(new Dropdown.OptionData("new selection" )); dropdown.options = options }
35.常用的UI组件
Vertical Latout Gropu 可以用于多个元素之间控制相同的距离和宽度
Grid 网格布局