Unity API常用方法和类学习笔记1

------主要构架(Unity-Engine、GameObject、Component)

事件

一、事件执行顺序

二、测试代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class API01EventFunction : MonoBehaviour
{void Reset(){Debug.Log("Reset");//当脚本被附加到对象上时或被重置时}void Awake(){Debug.Log("Awake");}void OnEnable() {Debug.Log("OnEnable");//当脚本所在对象被重新可见时}void Start(){Debug.Log("Start");}void FixedUpdate(){Debug.Log("FixedUpdate");//每秒有固定的调用次数,所以运行时不受电脑性能的差别影响——适合用于控制物体的运动}void Update(){Debug.Log("Update");//不固定,调用次数随电脑运行-画面加载快慢影响}void LateUpdate() {Debug.Log("LateUpdate");//跟随Update(一致)}void OnApplicationPause() {Debug.Log("OnApplicationPause");}void OnDisable() {Debug.Log("OnDisable");//当物体不可见时}void OnApplicationQuit() {Debug.Log("OnApplicationQuit");//退出时}void OnDestoy() {Debug.Log("OnDestroy");}
}

类Time

一、静态变量

 void Update () {Debug.Log("Time.deltaTime" + Time.deltaTime);//每一帧的时间间隔约等于1/60秒Debug.Log("Time.fixedDeltaTime" + Time.fixedDeltaTime);//固定的间隔时间Debug.Log("Time.fixedTime" + Time.fixedTime);//从游戏开始到游戏结束Debug.Log("Time.frameCount" + Time.frameCount);//帧数Debug.Log("Time.realtimeSinceStartup" + Time.realtimeSinceStartup);//从游戏开始到游戏结束的时间(暂停时仍继续计时)Debug.Log("Time.smoothDeltaTime" + Time.smoothDeltaTime);//较平滑的间隔时间Debug.Log("Time.time" + Time.time);//与Time.fixedTime差不多Debug.Log("Time.timeScale" + Time.timeScale);//设置时间比例Debug.Log("Time.timeSinceLevelLoad" + Time.timeSinceLevelLoad);//以场景为基准,加载新场景时重新开始计时Debug.Log("Time.unscaledTime" + Time.unscaledTime);}

二、利用Time.realtimeSinceStartup测试函数是否太耗费性能

 void Start () {//利用Time.realtimeSinceStartup测试函数是否太耗费性能float time1 = Time.realtimeSinceStartup;for (int i = 0; i < runCount; i++){Method1();}float time2 = Time.realtimeSinceStartup;Debug.Log("timeM1=" + (time2 - time1));float time3 = Time.realtimeSinceStartup;for (int i = 0; i < runCount; i++){Method2();}float time4 = Time.realtimeSinceStartup;Debug.Log("timeM2" + (time4 - time3));}void Method1() {int i = 1 + 2;}void Method2() {int i = 1 * 2;}
}

三、利用Time.deltaTime使物体运动符合物理规律

void Update () {cube.Translate(Vector3.forward);//每帧运行一米,每秒运行50米//处理方法:/ 50f——不符合物理规律(每帧的间隔长时和每帧的间隔短时都运行相同的距离)cube.Translate(Vector3.forward * Time.deltaTime);//运行距离随时间间隔变化而变化}

四、通过设置Time.timeScale = 0;来暂停游戏,但是需满足前提:所有控制物体的运动都有Time.deltaTime

Note:1为默认值,=0时,cube不动,因为每次得到的Time.deltaTime都会 * Time.timeScale)

游戏-场景-物体-组件

一、游戏-场景-物体-组件关系图

二、创建新物体

public class API03GameObject : MonoBehaviour {public GameObject prefab;public GameObject go;// Use this for initializationvoid Start () {//在Unity中创建新物体的三种方法//1、newGameObject go = new GameObject("Cube");//2、Instantiate//实例化Prefab 或 另外一个游戏物体(克隆)GameObject.Instantiate(prefab);//3、CreatePrimitive——创建基础图形GameObject.CreatePrimitive(PrimitiveType.Plane);GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);}
}

三、添加组件

public class API03GameObject : MonoBehaviour {public GameObject go;// Use this for initializationvoid Start () {GameObject go = new GameObject("Cube");//在Unity中为物体添加组件//1、拖拽//2、代码调用方法go.AddComponent<Rigidbody>();//Unity自带组件//go.AddComponent<API01EventFunction>();//或编辑的脚本}
}

UnityEngine-GameObject-Component关系图

类GameObject和类Component共有方法和变量

一、静态变量

     Debug.Log(go.name);Debug.Log(go.GetComponent<Transform>().name);

二、静态方法

     //1、FindObjectOfTypeLight light = FindObjectOfType<Light>();//或者GameObject.FindObjectOfType<Light>();light.enabled = false;//2、FindGameObjectsOfType——返回数组; 不查找 未激活的游戏物体Transform[] ts = FindObjectsOfType<Transform>();foreach (Transform t in ts){Debug.Log(t);//显示:游戏物体名字(组件名字);用t.name:游戏物体名字}

三、公有方法

public GameObject target;//将消息接收目标传入父物体组件中void Start () {//1、发送消息Message——消息传送不到未激活的物体上,物体也不会做出响应;//(1)BroadcastMessage——广播发送消息target.BroadcastMessage("Attack", null, SendMessageOptions.DontRequireReceiver);//null——传参;SendMessageOptions.DontRequireReceiver——控制若未查找到消息接收者是否报错//注:目标物体的子物体也会接收到消息并作出响应//(2)SendMessage——一对一发送消息target.SendMessage("Attack", null, SendMessageOptions.DontRequireReceiver);//目标物体的子物体不会接收到消息//(3)SendMessageUpwards——当前物体以及它所有的父物体target.SendMessageUpwards("Attack", null, SendMessageOptions.DontRequireReceiver);//2、GetComponent---查找组件//(1)Cube cube = target.GetComponent<Cube>();Transform t = target.GetComponent<Transform>();Debug.Log(cube);Debug.Log(t);Debug.Log("---------------------------");//(2)Cube[] cubes = target.GetComponents<Cube>();Debug.Log(cubes.Length);Debug.Log("---------------------------");//(3)cubes = target.GetComponentsInChildren<Cube>();foreach (Cube c in cubes){Debug.Log(c);}Debug.Log("---------------------------");//(4)cubes = target.GetComponentsInParent<Cube>();foreach (Cube c in cubes){Debug.Log(c);}}

四、常用变量、方法图

类GameObject

一、普通变量

        Debug.Log(go.activeInHierarchy);//将物体状态改为未激活状态,不耗费性能、不运行Update、不需要计算、不需要渲染,但仍占内存,随时可被重新启用

二、公有方法

     go.SetActive(false);//设置物体的状态(是否激活)Debug.Log(go.tag);

三、静态方法

        //1、Find——根据物体名字查找,遍历场景中所有物体,耗费性能大GameObject go = GameObject.Find("Main Camera");//不可直接Find ——GameObject方法而非Component方法go.SetActive(false);//2、FindGameObjectsWithTag——返回数组GameObject[] goes = GameObject.FindGameObjectsWithTag("Main Camera");//此处需判断数组是否为空,避免造成下面操作空引用goes[0].SetActive(false);//3、FindWithTag——仅返回查找到的第一个GameObjectGameObject go = GameObject.FindGameObjectWithTag("Main Camera1");//此处需判断go是否为空,避免造成下面操作空引用go.SetActive(false);

四、常用变量、方法图

类MonoBehaviour

Component–Behaviour–MonoBehaviour

一、继承成员——变量

 public Cube cube;void Start () {//组件自身——脚本API06MonoBehaviourDebug.Log(this.isActiveAndEnabled);Debug.Log(this.enabled);//可设置属性//以上皆可判断组件的激活状态enabled = false;//禁用组件——禁用的是脚本里的Update方法//注:以下输出的都是组件所在游戏物体的信息Debug.Log(name);Debug.Log(tag);Debug.Log(gameObject);Debug.Log(transform);//其他组件——组件之间的调用,此处为脚本CubeDebug.Log(cube.isActiveAndEnabled);Debug.Log(cube.enabled);cube.enabled = false;Debug.Log(cube.name);Debug.Log(cube.tag);Debug.Log(cube.gameObject);Debug.Log(cube.transform);}

二、静态方法

public class API06MonoBehaviour : MonoBehaviour {void Start () {//仅所在脚本继承自MonoBehaviour类情况下print("haha");//为MonoBehaviour中的静态方法//Debug.Log()  类名+静态方法}
}

三、公有方法
1、Invoke & InvokeRepeating & CancelInvoke

 void Start () {Invoke("Attack", 3f);//仅调用一次Attack方法,调用完之后返回falseInvokeRepeating("Attack", 4, 2);//4几秒之后开始调用,2隔几秒调用一次CancelInvoke("Attack");//不指定参数"Attack"则将所有Invoke都取消(此处一直返回false——Start先执行)}void Update () {bool res = IsInvoking("Attack");print(res);}void Attack(){print("正在攻击");}

2、协程方法Coroutine——不被等待运行完成,与后面的语句同步执行
(1)Coroutines的特点:
返回值是IEnumerator
返回参数的时候使用yield return null/0;
协程方法的调用StartCoroutine(methodname());

     public GameObject cube;void Start () {print("ha");//普通方法执行例子//ChangeColor();//协程方法执行//StartCoroutine(ChangeColor());//ChangeColor()与下面代码print("haha");同步运行print("haha");}void ChangeColor(){print("hahaha");cube.GetComponent<MeshRenderer>().material.color = Color.blue;print("hahahaha");}IEnumerator ChangeColor(){print("hahaha");yield return new WaitForSeconds(3);//暂停(延迟)运行cube.GetComponent<MeshRenderer>().material.color = Color.blue;print("hahahaha");yield return null;}

(2)小实验:利用协程方法实现颜色渐变动画

 public GameObject cube;private IEnumerator ie;void Update () {if (Input.GetKeyDown(KeyCode.Space)){ie = Fade();//开启和停止协程时,需保证传入的参数类型一致//1、IEnumeratorStartCoroutine(ie);//2、string methodName//StartCoroutine("Fade");//StartCoroutine(Fade());}if (Input.GetKeyDown(KeyCode.S)){   //两种使用方法://1、public void StopCoroutine(IEnumerator routine);StopCoroutine(ie);//2、public void StopCoroutine(string methodName);//StopCoroutine("Fade");}}IEnumerator Fade(){//法一、协程for (float i = 0; i <= 1; i += 0.1f){cube.GetComponent<MeshRenderer>().material.color = new Color(i, i, i, i);yield return new WaitForSeconds(0.1f);}//法二、差值运算for (; ; ){Color color = cube.GetComponent<MeshRenderer>().material.color;Color newColor = Color.Lerp(color, Color.red, 0.02f);cube.GetComponent<MeshRenderer>().material.color = newColor;yield return new WaitForSeconds(0.02f);if (Mathf.Abs(Color.red.g - newColor.g) <= 0.01f){break;}}}

3、消息Message

 void OnMouseDown(){Debug.Log("Down" + gameObject);}void OnMouseUp(){Debug.Log("Up" + gameObject);}void OnMouseOver(){Debug.Log("Over" + gameObject);//每帧执行}void OnMouseDrag()//鼠标抬起位置改变时,触发的仍是按下时所在物体的Up事件{Debug.Log("Drag" + gameObject);}void OnMouseEnter(){Debug.Log("Enter" + gameObject);}void OnMouseExit(){Debug.Log("Exit" + gameObject);}//用于处理单击某一物体事件//Button在鼠标抬起时触发——触发条件:鼠标按下和抬起在同一个物体上void OnMouseUpAsButton(){print("Button" + gameObject);}//注:物体Colliders是Trigger类型时,需保证开启了Trigger检测

Unity API常用方法和类学习笔记1相关推荐

  1. Unity API常用方法和类学习笔记2

    Unity API常用方法和类学习笔记2 ------Mathf & Input & Vector & Random 类Mathf 一.静态变量 print(Mathf.Deg ...

  2. 《Unity API常用方法和类详细讲解—Siki学院》课程学习笔记02

    <Unity API常用方法和类详细讲解-Siki学院>课程学习笔记02 课时10 GameObject.Component和Object的千丝万缕的关系 一个游戏由多个场景组成,一个场景 ...

  3. 《Unity API常用方法和类详细讲解—Siki学院》课程学习笔记03

    <Unity API常用方法和类详细讲解-Siki学院>课程学习笔记03 课时18-20协程及其执行 1.使用Coroutine实现颜色动画渐变 void Update(){if (Inp ...

  4. Unity API常用方法和类

    什么是API?--预先设置好的编程接口 事件函数及常用脚本 事件函数的执行顺序 具体可参考:docs.unity.cn/cn/current/Manual/ExecutionOrder.html *函 ...

  5. Unity API常用方法和类的解析

    一.事件函数执行的先后顺序 FixedUpdate每秒执行固定次数,应该将处理跟物理相关的运动的代码放在FixedUpdate中. Update和LateUpdate跟硬件和代码性能有关,每秒执行次数 ...

  6. Unity开发基础——使用字符串学习笔记

    蓝鸥Unity开发基础使用字符串学习笔记 本节内容:使用字符串:字符串拼接.转义字符 一.字符串拼接:字符串可以使用+或+=进行字符串拼接!! using System; namespace Less ...

  7. Unity的VRTK捡拾物体学习笔记

    Unity的VRTK捡拾物体学习笔记 1.VRTK捡拾物体设置: 2.VRTK可交互对象设置: 3.触摸设置: 4.触摸设置2:

  8. QIODevice 类学习笔记

    QIODevice 类学习笔记 Isaaccwoo 2015年12月10日 一.       简介 QIODevice用于对输入输出设备进行管理.输入设备有两种类型,一种是随机访问设备(Random- ...

  9. QFrame类学习笔记

    QFrame类学习笔记 参考:https://wenku.baidu.com/view/759c1af565ce050877321322.html https://doc.qt.io/qt-5/qfr ...

最新文章

  1. java免费低代码开发平台,steedos-platform
  2. 文巾解题 53. 最大子序和
  3. 自考计算机科学与技术本科毕业论文选题,自考计算机科学与技术专业(本)毕业论文写作指导...
  4. jquery 选择器,模糊匹配
  5. 深信服上网管理设备恢复控制台密码
  6. java streams_使用Stream.peek在Java Streams内部进行窥视
  7. Summer training round2 #10(Training 30)
  8. python的sort()和sorted()的区别_Python 3中sort()和sorted()的区别和用法,Python3
  9. html5学习笔记---01.HTML5介绍,02.HTML5的新特性
  10. [Asp.net]Uploadify上传大文件,Http error 500 解决方案
  11. 好程序员web前端分享逻辑运算
  12. opencv基础:罗德里格斯旋转公式(Rodrigues' rotation formula)推导 rodrigues()函数原理
  13. 豆瓣关于计算机视觉的书评及介绍
  14. 913微型计算机原理,微机原理与接口技术(铁道大学)第9章定时器计数器.ppt
  15. 应用计算机测定线性电阻伏安特性实验结论,线性电阻和非线性电阻伏安特性曲线测定实验报告(共8篇).docx...
  16. 计算机辅助药物设计的心得,计算机辅助药物设计实验的探索与心得.doc
  17. 大厂经典数据库(MongoDB)面试题整理汇总
  18. 字谜 大小写重复全排列问题
  19. 【JavaScript笔记 · 基础篇(五)】Array全家桶(引用数据类型中的数组 / Array对象 / Array.prototype)
  20. 混合云市场现状与发展趋势研究

热门文章

  1. mysql求学号的总分_有一个student表,有学号,姓名,科目,成绩等字段,请写一条sql语句,算出学生的总分数?...
  2. ns-3-model-library wifi 浅析_ns-3wifi部分解析_ns-3网络模拟器wifi部分文档分析_Part1
  3. java web调用百度地图_Java web与web gis学习笔记(二)——百度地图API调用
  4. PostgreSQL 之 学籍管理示例
  5. 分享 6 个 Vue3 开发必备的 VSCode 插件
  6. 在Windows服务器上搭建Nuget私人服务器(超~详细)
  7. APT32F102-SIO模块控制WS2812
  8. MFC CTreeCtrl节点重命名
  9. Javris OJ - pwn level5(mmap和mprotect练习)(_libc_csu_init中的通用gedget的使用)
  10. 维克森林大学计算机科学专业好不好,备受推崇的维克森林大学到底是什么样的?...