瞭解UNITY中的多執行緒及使用多執行緒
阿新 • • 發佈:2019-02-01
有些不涉及U3D API的計算可以放在分執行緒裡,能提高多核CPU的使用率。
總結:
0. 變數(都能指向相同的記憶體地址)都是共享的
1. 不是UnityEngine的API能在分執行緒執行
2. UnityEngine定義的基本結構(int,float,Struct定義的資料型別)可以在分執行緒計算
如 Vector3(Struct)可以 , 但Texture2d(class,根父類為Object)不可以。
3
UnityEngine定義的基本型別的函式可以在分執行緒執行,如
其他transform.position,Texture.Apply()等等都不能在分執行緒裡執行。
結論: 分執行緒可以做 基本型別的計算, 以及非Unity(包括.Net及SDK)的API
例1:在分執行緒裡print資訊
- int i = 99;
- print (i.ToString());
- Vector3 x = new Vector3(0,0,9);
- x.Normalize();
類的函式不能在分執行緒執行
obj.name 實際是get_name函式 分執行緒報錯誤:get_name can only be called from the main thread.Texture2D tt = new Texture2D(10,10);
實際會呼叫UnityEngine裡的Internal_Create
分執行緒報錯誤:Internal_Create can only be called from the main thread.
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Threading;
- public class Manager : MonoBehaviour {
- void Start () {
- Thread t = new Thread(new ThreadStart(Cal));
- t.Start();
- }
- void Cal()
- {
- print ("Hello world!");
- }
- }
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Threading;
- public class Manager : MonoBehaviour {
- public int index;
- void Start () {
- index = 0;
- Thread t = new Thread(new ThreadStart(Cal));
- t.Start();
- }
- void Update () {
- print("index: "+index);
- }
- void Cal()
- {
- index = 10;
- }
- }
例3:計算Vector3
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Threading;
- public class Manager : MonoBehaviour {
- public Vector3 vec;
- void Start () {
- vec = new Vector3(0,0,0);
- Thread t = new Thread(new ThreadStart(Cal));
- t.Start();
- }
- void Update () {
- print(vec);
- }
- void Cal()
- {
- vec = new Vector3(10,20,0);
- }
- }
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Threading;
- public class Manager : MonoBehaviour {
- public Texture2D t2d;
- void Start () {
- Thread t = new Thread(new ThreadStart(Cal));
- t.Start();
- }
- void Cal()
- {
- Vector3 x = new Vector3(0,0,9);
- print(x);
- }
- }
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Threading;
- public class Manager : MonoBehaviour {
- public Texture2D t2d;
- void Start () {
- Thread t = new Thread(new ThreadStart(Cal));
- t.Start();
- }
- void Cal()
- {
- Vector3 x = new Vector3(0,0,9);
- x.Normalize();
- print(x);
- }
- }