Unity3D自己常用代码

常需要,常查找!

自己记录下!

1.

[csharp] view plain copy
 
 print?
  1. var ray = Camera.main.ScreenPointToRay(Input.mousePosition);  
  2.     //GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = ray.GetPoint(10.0f);  
  3.     transform.LookAt(ray.GetPoint(10.0f));  


2.

提高效率

[html] view plain copy
 
 print?
  1. GetComponent(), FindObjectByType() and Instantiate()  

尽量少使用。

3. InvokeReapting 的内部实现

[html] view plain copy
 
 print?
  1. 实现过程  
  2. {  
  3.    找到函数方法名称,存储  
  4. 等待调用时间,WaitForSeconds(time)  
  5. 循环知道用户取消  
  6. {  
  7. Invoke 存储的函数方法  
  8. 等待时间  
  9. }  
  10. 删除记录保存的方法  
  11. }  

4. 

Coroutine 和InvokeReapting

协同程序,不是多线程。但是他有自己的堆栈,局部变量,指令指针,与其他协同程序共享全局变量等信息。在多处理器下,多线程同时运行,协同程序,在某时刻之有一个在运行。

若你有个负责的任务,它非常费帧率,就考虑使用协同或InvokeReapting.

若是简单任务,就嫑在协同或InvokeReapting使用,这不会提高效率的。

但是也不用太死板。尽管可能降低效率,代码会更简单和实用。

协同是处理时间序列的一种很好的方法。

它不是线程也不是异步。

协同当脚本未激活或对象为激活时不可用。

协同返回时间的WaitForSeconds依赖于Time.timeScale.

[html] view plain copy
 
 print?
  1. InvokeReapting  
  2.    
  3. /*  
  4. void InvokeRepeating(string methodName, float time, float repeatRate)  
  5. {  
  6.    - Find the method called "methodName" in the calling assembly and store it.  
  7.    - Wait "time" seconds by yielding on WaitForSeconds(time)  
  8.    Loop until the user cancels this action  
  9.    {  
  10.       - Invoke the stored method  
  11.       - Wait "repeatTime" seconds by yielding on WaitForSeconds(repeatRate)  
  12.    }  
  13.    - Remove the method info record from storage.  
  14. }  
  15. */  

使用Invoke或InvokeReapting,这样很难调试。

原文地址:https://www.cnblogs.com/chenliyang/p/6558508.html