My problem is I try to use Unity socket to implement something. Each time, when I get a new message I need to update it to the updattext (it is a Unity Text). However, When I do the following code, the void update does not calling every time.
The reason for I do not include updatetext.GetComponent<Text>().text = "From server: "+tempMesg;in the void getInformation is this function is in the thread, when I include that in getInformation() it will come with an error:
getcomponentfastpath can only be called from the main thread
I think the problem is I don't know how to run the main thread and the child thread in C# together? Or there maybe other problems.
Here is my code:
using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;
public class Client : MonoBehaviour {
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
private Thread oThread;
// for UI update
public GameObject updatetext;
String tempMesg = "Waiting...";
// Use this for initialization
void Start () {
updatetext.GetComponent<Text>().text = "Waiting...";
clientSocket.Connect("10.132.198.29", 8888);
oThread = new Thread (new ThreadStart (getInformation));
oThread.Start ();
Debug.Log ("Running the client");
}
// Update is called once per frame
void Update () {
updatetext.GetComponent<Text>().text = "From server: "+tempMesg;
Debug.Log (tempMesg);
}
void getInformation(){
while (true) {
try {
NetworkStream networkStream = clientSocket.GetStream ();
byte[] bytesFrom = new byte[10025];
networkStream.Read (bytesFrom, 0, (int)bytesFrom.Length);
string dataFromClient = System.Text.Encoding.ASCII.GetString (bytesFrom);
dataFromClient = dataFromClient.Substring (0, dataFromClient.IndexOf ("$"));
Debug.Log (" >> Data from Server - " + dataFromClient);
tempMesg = dataFromClient;
string serverResponse = "Last Message from Server" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes (serverResponse);
networkStream.Write (sendBytes, 0, sendBytes.Length);
networkStream.Flush ();
Debug.Log (" >> " + serverResponse);
} catch (Exception ex) {
Debug.Log ("Exception error:" + ex.ToString ());
oThread.Abort ();
oThread.Join ();
}
// Thread.Sleep (500);
}
}
}
Unity is not Thread safe, so they decided to make it impossible to call their API from another Thread by adding a mechanism to throw an exception when its API is used from another Thread.
This question has been asked so many times, but there have been no proper solution/answer to any of them. The answers are usually "use a plugin" or do something not thread-safe. Hopefully, this will be the last one.
The solution you will usually see on Stackoverflow or Unity's forum website is to simply use a boolean variable to let the main thread know that you need to execute code in the main Thread. This is not right as it is not thread-safe and does not give you control to provide which function to call. What if you have multiple Threads that need to notify the main thread?
Another solution you will see is to use a coroutine instead of a Thread. This does not work. Using coroutine for sockets will not change anything. You will still end up with your freezing problems. You must stick with your Thread code or use Async.
One of the proper ways to do this is to create a collection such as List. When you need something to be executed in the main Thread, call a function that stores the code to execute in an Action. Copy that List of Action to a local List of Action then execute the code from the local Action in that List then clear that List. This prevents other Threads from having to wait for it to finish executing.
You also need to add a volatile boolean to notify the Update function that there is code waiting in the List to be executed. When copying the List to a local List, that should be wrapped around the lock keyword to prevent another Thread from writing to it.
A script that performs what I mentioned above:
UnityThread Script:
#define ENABLE_UPDATE_FUNCTION_CALLBACK
#define ENABLE_LATEUPDATE_FUNCTION_CALLBACK
#define ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class UnityThread : MonoBehaviour
{
//our (singleton) instance
private static UnityThread instance = null;
////////////////////////////////////////////////UPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueUpdateFunc then executed from there
private static List<System.Action> actionQueuesUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesUpdateFunc to be executed
List<System.Action> actionCopiedQueueUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteUpdateFunc = true;
////////////////////////////////////////////////LATEUPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueLateUpdateFunc then executed from there
private static List<System.Action> actionQueuesLateUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesLateUpdateFunc to be executed
List<System.Action> actionCopiedQueueLateUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteLateUpdateFunc = true;
////////////////////////////////////////////////FIXEDUPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueFixedUpdateFunc then executed from there
private static List<System.Action> actionQueuesFixedUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesFixedUpdateFunc to be executed
List<System.Action> actionCopiedQueueFixedUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteFixedUpdateFunc = true;
//Used to initialize UnityThread. Call once before any function here
public static void initUnityThread(bool visible = false)
{
if (instance != null)
{
return;
}
if (Application.isPlaying)
{
// add an invisible game object to the scene
GameObject obj = new GameObject("MainThreadExecuter");
if (!visible)
{
obj.hideFlags = HideFlags.HideAndDontSave;
}
DontDestroyOnLoad(obj);
instance = obj.AddComponent<UnityThread>();
}
}
public void Awake()
{
DontDestroyOnLoad(gameObject);
}
//////////////////////////////////////////////COROUTINE IMPL//////////////////////////////////////////////////////
#if (ENABLE_UPDATE_FUNCTION_CALLBACK)
public static void executeCoroutine(IEnumerator action)
{
if (instance != null)
{
executeInUpdate(() => instance.StartCoroutine(action));
}
}
////////////////////////////////////////////UPDATE IMPL////////////////////////////////////////////////////
public static void executeInUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesUpdateFunc)
{
actionQueuesUpdateFunc.Add(action);
noActionQueueToExecuteUpdateFunc = false;
}
}
public void Update()
{
if (noActionQueueToExecuteUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueUpdateFunc queue
actionCopiedQueueUpdateFunc.Clear();
lock (actionQueuesUpdateFunc)
{
//Copy actionQueuesUpdateFunc to the actionCopiedQueueUpdateFunc variable
actionCopiedQueueUpdateFunc.AddRange(actionQueuesUpdateFunc);
//Now clear the actionQueuesUpdateFunc since we've done copying it
actionQueuesUpdateFunc.Clear();
noActionQueueToExecuteUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueUpdateFunc
for (int i = 0; i < actionCopiedQueueUpdateFunc.Count; i++)
{
actionCopiedQueueUpdateFunc[i].Invoke();
}
}
#endif
////////////////////////////////////////////LATEUPDATE IMPL////////////////////////////////////////////////////
#if (ENABLE_LATEUPDATE_FUNCTION_CALLBACK)
public static void executeInLateUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesLateUpdateFunc)
{
actionQueuesLateUpdateFunc.Add(action);
noActionQueueToExecuteLateUpdateFunc = false;
}
}
public void LateUpdate()
{
if (noActionQueueToExecuteLateUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueLateUpdateFunc queue
actionCopiedQueueLateUpdateFunc.Clear();
lock (actionQueuesLateUpdateFunc)
{
//Copy actionQueuesLateUpdateFunc to the actionCopiedQueueLateUpdateFunc variable
actionCopiedQueueLateUpdateFunc.AddRange(actionQueuesLateUpdateFunc);
//Now clear the actionQueuesLateUpdateFunc since we've done copying it
actionQueuesLateUpdateFunc.Clear();
noActionQueueToExecuteLateUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueLateUpdateFunc
for (int i = 0; i < actionCopiedQueueLateUpdateFunc.Count; i++)
{
actionCopiedQueueLateUpdateFunc[i].Invoke();
}
}
#endif
////////////////////////////////////////////FIXEDUPDATE IMPL//////////////////////////////////////////////////
#if (ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK)
public static void executeInFixedUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesFixedUpdateFunc)
{
actionQueuesFixedUpdateFunc.Add(action);
noActionQueueToExecuteFixedUpdateFunc = false;
}
}
public void FixedUpdate()
{
if (noActionQueueToExecuteFixedUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueFixedUpdateFunc queue
actionCopiedQueueFixedUpdateFunc.Clear();
lock (actionQueuesFixedUpdateFunc)
{
//Copy actionQueuesFixedUpdateFunc to the actionCopiedQueueFixedUpdateFunc variable
actionCopiedQueueFixedUpdateFunc.AddRange(actionQueuesFixedUpdateFunc);
//Now clear the actionQueuesFixedUpdateFunc since we've done copying it
actionQueuesFixedUpdateFunc.Clear();
noActionQueueToExecuteFixedUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueFixedUpdateFunc
for (int i = 0; i < actionCopiedQueueFixedUpdateFunc.Count; i++)
{
actionCopiedQueueFixedUpdateFunc[i].Invoke();
}
}
#endif
public void OnDisable()
{
if (instance == this)
{
instance = null;
}
}
}
USAGE:
This implementation allows you to call functions in the 3 most used Unity functions: Update, LateUpdate and FixedUpdate functions. This also allows you call run a coroutine function in the main Thread. It can be extended to be able to call functions in other Unity callback functions such as OnPreRender and OnPostRender.
1.First, initialize it from the Awake() function.
void Awake()
{
UnityThread.initUnityThread();
}
2.To execute a code in the main Thread from another Thread:
UnityThread.executeInUpdate(() =>
{
transform.Rotate(new Vector3(0f, 90f, 0f));
});
This will rotate the current Object the scipt is attached to, to 90 deg. You can now use Unity API(transform.Rotate) in another Thread.
3.To call a function in the main Thread from another Thread:
Action rot = Rotate;
UnityThread.executeInUpdate(rot);
void Rotate()
{
transform.Rotate(new Vector3(0f, 90f, 0f));
}
The #2 and #3 samples executes in the Update function.
4.To execute a code in the LateUpdate function from another Thread:
Example of this is a camera tracking code.
UnityThread.executeInLateUpdate(()=>
{
//Your code camera moving code
});
5.To execute a code in the FixedUpdate function from another Thread:
Example of this when doing physics stuff such as adding force to Rigidbody.
UnityThread.executeInFixedUpdate(()=>
{
//Your code physics code
});
6.To Start a coroutine function in the main Thread from another Thread:
UnityThread.executeCoroutine(myCoroutine());
IEnumerator myCoroutine()
{
Debug.Log("Hello");
yield return new WaitForSeconds(2f);
Debug.Log("Test");
}
Finally, if you don't need to execute anything in the LateUpdate and FixedUpdate functions, you should comment both lines of this code below:
//#define ENABLE_LATEUPDATE_FUNCTION_CALLBACK
//#define ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK
This will increase performance.
I have been using this solution to this problem. Create a script with this code and attach it to a Game Object:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using UnityEngine;
public class ExecuteOnMainThread : MonoBehaviour {
public static readonly ConcurrentQueue<Action> RunOnMainThread = new ConcurrentQueue<Action>();
void Update()
{
if(!RunOnMainThread.IsEmpty)
{
while(RunOnMainThread.TryDequeue(out var action))
{
action?.Invoke();
}
}
}
}
Then when you need to call something on the main thread and access the Unity API from any other function in your application:
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
// Code here will be called in the main thread...
});
Much of the writing about threads in Unity is incorrect.
How so?
Unity is, of course, totally frame-based.
When you work in a frame-based system, threading issues are completely different.
Threading issues on a frame-based system are completely different. (In fact, often much easier to deal with.)
Let's say you have a Unity thermometer display that shows some value
Thermo.cs
So it will have a function which is called in Update, like
func void ShowThermoValue(float fraction) {
display code to show the current thermometer value
}
Recall that the "Update" function in Unity simply means "run this once each frame".
That only runs once per frame, and that's that.
(Naturally, it runs only on the "main thread". There's nothing else in Unity! There's just ... "the Unity thread"!)
Somewhere else, perhaps in "IncomingData.cs", you will have a function which handles the concept "a new value has arrived":
[MonoPInvokeCallback(typeof(ipDel))]
public static void NewValueArrives(float f) {
... ???
}
Note that, of course, that is a class function! What else can it be?
You can't "reach in to" a normal Unity function. (Such as ShowThermoValue.) That would be meaningless - it's just a function which runs once each frame.Footnote 1
Let's say: values arrive very frequently and irregularly.
Image you have some sort of scientific devices (perhaps IR thermometers) connected connected to a rack of PCs
Those electronic devices deliver new "temperature" values very often. Let's say dozens of times per frame.
So, "NewValueArrives" is being called 100s of times a second.
So what do you do with the values?
It could not be simpler.
From the arriving-values thread, all you do is ................. wait for it ............. set a variable in the component!!
WTF? All you do is set a variable? That's it? How can it be that simple?
This is one of those unusual situations:
Much of the writing on threads in Unity is, simply, completely hopeless.
Surprisingly, the actual approach is extremely simple.
It's so simple you may think you are doing something wrong!!
So have the variable ...
[System.Nonserialized] public float latestValue;
Set it from the "arriving thread" ...
[MonoPInvokeCallback(typeof(ipDel))]
public static void NewValueArrives(float f) {
ThisScript.runningInstance.latestValue = f; // done
}
Honestly that's it.
Essentially, to be the world's greatest expert at "threading in Unity" - which is, obviously, frame-based - there's nothing more to do than the above.
And whenever ShowThermoValue is called each frame ...................... simply display that value!
Really, that's it!
[System.Nonserialized] public float latestValue;
func void ShowThermoValue() { // note NO arguments here!
display code, draws a thermometer
thermo height = latestValue
}
You're simply displaying the "latest" value.
latestValue may have been set once, twice, ten times, or a hundred times that frame ............ but, you simply display whatever is the value when ShowThermoValue runs that frame!
What else could you display?
The thermometer is updating at 60fps on-screen so you display the latest value. Footnote 2
It's actually that easy. It's just that easy. Surprising but true.
#(Critical aside - don't forget that vector3, etc, are NOT Atomic in Unity/C#)
As user #dymanoid has pointed out (read the important discussion below) it's critical to remember that while float is atomic in the Unity/C# milieu, anything else (say, Vector3 etc) IS NOT ATOMIC. Typically (as in the example here) you only pass floats around from calculations from, say, native plugins, thermometers etc. But it's essential to be aware that vectors and so on are NOT atomic.
Sometimes experienced threading programmers get in a knot with a frame-based system, because: in a frame based system most of the problems caused by racetrack and locking issues ... do not exist conceptually.
In a frame-based system, any game items should simply be displaying or behaving based on some "current value," which is set somewhere. If you have info arriving from other threads, just set those values - you're done.
You can not meaningfully "talk to the main thread" in Unity because that main thread ............. is frame-based!
Most locking, blocking and racetrack issues are non-existent in the frame-based paradigm because: if you set latestValue ten times, a million times, a billion times, in one particular frame .. what can you do? .. you can only display one value during that frame!
Think of an old-fashioned plastic film. You literally just have ...... a frame, and that's it. If you set latestValue a trillion times in one particular frame, ShowThermoValue will simply display (for that 60th of a second) the one value it grabs when it is run.
All you do is: leave information somewhere, which, the frame-paradigm system will utilize during that frame if it wants to.
That's it in a nutshell.
Thus, most "threading issues" disappear in Unity.
All you can do from
other calculation threads or
from plugin threads,
is just "drop-off values" which the game may use.
That's it!
Let's consider the question title...
How do you "... call a function in the main Thread"
This is completely meaningless. The "functions" in Unity are simply functions which the frame engine runs once per frame.
You can't "call" anything in Unity. The frame engine runs a number of things (many things) once per frame.
Note that indeed threads are totally irrelevant. If Unity ran with a billion threads, or with quantum computing, it would have no bearing on anything.
You can't "call a function" in a frame-based system.
Fortunately, the approach to take is dead simple, you just set values, which the frame-based functions can look at when they want! It's really that easy.
Footnotes
1 How could you? As a thought experiment, forget about the issue that you're on a different thread. ShowThermoValue is run once a frame by the frame engine. You can't "call" it in any meaningful way. Unlike in normal OO software, you cannot, say, instantiate an instance of the class (a Component?? meaningless) and run that function - that is completely meaningless.
In "normal" threaded programming, threads can talk back and fore and so on, and in doing so you have concerns about locking, racetrack and so on. But that is all meaningless in an ECS, frame-based, system. There is nothing to "talk to".
Let's say that Unity was in fact multithreaded!!!! So the Unity guys have all of the engine running in a multithreaded manner. It wouldn't make any difference - you can not get "in to" ShowThermoValue in any meaningful way! It's a Component which the frame engine runs once a frame and that's that.
So NewValueArrives is not anywhere - it's a class function!
Let's answer the question in the headline:
"Use Unity API from another Thread or call a function in the main Thread?"
The concept is >> completely meaningless <<. Unity (like all game engines) is frame-based. There's no concept of "calling" a function on the main thread. To make an analogy: it would be like a cinematographer in the celluloid-film era asking how to "move" something actually on one of the frames.
Of course that is meaningless. All you can do is change something for the next photo, the next frame.
2 I refer to the "arriving-values thread" ... in fact! NewValueArrives may, or may not, run on the main thread!!!! It may run on the thread of the plugin, or on some other thread! It may actually be completely single-threaded by the time you deal with the NewValueArrives call! It just doesn't matter! What you do, and all you can do, in a frame-based paradigm, is, "leave laying around" information which Components such as ShowThermoValue, may use, as, they see fit.
Another solution to run code on the main thread, but without requiring a game object and MonoBehavior, is to use SynchronizationContext:
// On main thread, during initialization:
var syncContext = System.Threading.SynchronizationContext.Current;
// On your worker thread
syncContext.Post(_ =>
{
// This code here will run on the main thread
Debug.Log("Hello from main thread!");
}, null);
Use UniRx's multithreading pattern, UniTask and RxSocket together.
[SerializeField] private Text m_Text;
async UniTaskVoid Connect() {
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 12345);
// Create a socket client by connecting to the server at the IPEndPoint.
// See the UniRx Async tooling to use await
IRxSocketClient client = await endPoint.ConnectRxSocketClientAsync();
client.ReceiveObservable
.ToStrings()
.ObserveOnMainThread()
.Subscribe(onNext: message =>
{
m_Text.text = message;
}).AddTo(this);
// Send a message to the server.
client.Send("Hello!".ToByteArray());
}
Related
I'm new to unity. I have 4 GameObjects say Red, Green, Blue, Yellow - with index mapped 0, 1, 2 and 3 respectively. Also, I kept index sequence in the list List<int> systemTrack.
Now, I'm calling the sequence of animator with respect to list { 0, 1, 2, 3 } (this can be random 0-3).
I can perform one animator loop at a given time.
void Start() {
animator.Play("blue_animation", 0, 0);
}
How can I call in sequence based on list ? Perhaps Update() is right place to call.
So far I found this thread - But it has single Animator object with multiple state called in sequence which is not my case.
Few others discussions also available for Animation component Not for the new Animator component.
In your current class you could use a Coroutine like
List<AnimatorQueueController> animatorQueues;
private void Start()
{
StartCoroutine(RunAllControllersSequencial());
}
IEnumerator RunAllControllersSequencial()
{
foreach (var queue in animatorQueues)
{
// This runs the routine and waits until it finishes
yield return queue.RunAnimationQueueAndWait();
}
}
Now the only thing to do is define/implement how each if these controllers "knows", that its own animation queue has finished.
There are probably many possible ways to go. Straight away: None of them will be beautiful ;) Since the Animator uses a lot of string based stuff you always will end up either having to make sure all animation/trigger names are written correctly, or you will have to reference the animationClip and either hope the state is called the same or you have to expensively find the states via the according clip, you'd have to know how much time to wait for the queue to finish, etc.
This said, also this solution won't be perfect but in my opinion for your setup it would be the most convenient ;)
You could e.g. use an Animation Event and do something like
public class AnimationQueueController : MonoBehaviour
{
[SerializeField] private Animator _animator;
// Here set the first state name for each instance via the Inspector
[SerializeField] private string firstStateName = "first_state";
private void Awake ()
{
if(!_animator) _animator = GetComponent<Animator>();
}
// Simply have another routine you can yield so it is executed and at the same time waits until it is done
public IEnumerator RunAnimationQueueAndWaitUntilEnd()
{
hasReachedEnd = false;
_animator.Play(firstStateName, 0 ,0);
yield return new WaitUntil(() => hasReachedEnd);
}
// This is the method you will invoke via the Animation Event
// See https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
public void AnimationEnd()
{
hasReachedEnd = true;
}
}
This at least reduces your implementation overhead to
make sure you fire the Animation Event at the end of the last state
make sure you provide the name of the first state in the AnimatorQueueController
in your original script instead of Animator references rather store the AnimatorQueueController in your list
This is a short one that I have been unable to google a clear answer for.
Basically, I’m working with pixels but I want to put it on a second thread so UI and everything runs during expensive operations.
Are Vector4s, which are implicitly convertable to and from Color, allowed on other threads even though Unity isn’t thread safe?
Basically, how would I go about doing color operations without Color struct or Vector4s (if those don’t work either)?
In short: YES! (as long as you don't read/write them at the same time of course).
In long:
Only those parts that directly require or influence the Scene itself are not usable from any other threads than the Unity "main" thread. Unity immediately blocks it and shows a warning. So what you can not do is e.g. setting or getting Transform properties, trying to access .gameObject on any Component, anything related to Texture2D, stuff like GetComponent, Find etc.
structs, however, like Vector4, Color, Quaternion etc are just basic data containers holding some values and doing some pure mathematical operations on them ... they can be used in any background thread in order to process them.
Even your own MonoBehaviour can possibly be used in background threads (you just pass in a reference) as long as you access only those fields and only call those methods, that - again - don't immediately require or influence the Scene.
However, they are not "thread-safe" themselves, meaning there is no lock going on. So of course you have to assure yourself that your threads (Unity main thread and background thread(s)) have exclusive access to your values, meaning only exactly one thread may be reading and writing at the same time.
Something like this is completely valid:
private IEnumerator Start ()
{
Debug.Log("MainThread: Let's get some colors");
var stopWatch = new Stopwatch();
stopWatch.Restart();
var thread = new Thread(ColorThread);
thread.Start();
while (!ColorsReceived())
{
Debug.Log("MainThread: ... still waiting ...");
yield return new WaitForSeconds(0.5f);
}
lock(_lock)
{
Debug.Log($"MainThread: Got {colors.Length} colors after {stopWatch.ElapsedMilliseconds / 1000f} seconds");
}
}
private bool ColorsReceived()
{
lock(_lock)
{
return colors != null;
}
}
private void ColorThread()
{
Debug.Log("BackgroundThread: Started generating colors");
var output = new Color[1000];
var random = new System.Random();
for(var i = 0; i < output.Length;i++)
{
output[i] = new Color32((byte) random.Next(0, 256), (byte) random.Next(0, 256), (byte) random.Next(0, 256), (byte)random.Next(0,256));
}
// Do some havy stuff
Thread.Sleep(3000);
lock(_lock)
{
colors = output;
}
Debug.Log("BackgroundThread: Finished generating colors");
}
=>
MainThread: Lets's get some colors
MainThread: ... still waiting ...
BackgroundThread: Started generating colors
MainThread: ... still waiting ...
MainThread: ... still waiting ...
MainThread: ... still waiting ...
MainThread: ... still waiting ...
BackgroundThread: Finished generating colors
MainThread: Got 1000 colors after 3.19 seconds
My problem is I try to use Unity socket to implement something. Each time, when I get a new message I need to update it to the updattext (it is a Unity Text). However, When I do the following code, the void update does not calling every time.
The reason for I do not include updatetext.GetComponent<Text>().text = "From server: "+tempMesg;in the void getInformation is this function is in the thread, when I include that in getInformation() it will come with an error:
getcomponentfastpath can only be called from the main thread
I think the problem is I don't know how to run the main thread and the child thread in C# together? Or there maybe other problems.
Here is my code:
using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;
public class Client : MonoBehaviour {
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
private Thread oThread;
// for UI update
public GameObject updatetext;
String tempMesg = "Waiting...";
// Use this for initialization
void Start () {
updatetext.GetComponent<Text>().text = "Waiting...";
clientSocket.Connect("10.132.198.29", 8888);
oThread = new Thread (new ThreadStart (getInformation));
oThread.Start ();
Debug.Log ("Running the client");
}
// Update is called once per frame
void Update () {
updatetext.GetComponent<Text>().text = "From server: "+tempMesg;
Debug.Log (tempMesg);
}
void getInformation(){
while (true) {
try {
NetworkStream networkStream = clientSocket.GetStream ();
byte[] bytesFrom = new byte[10025];
networkStream.Read (bytesFrom, 0, (int)bytesFrom.Length);
string dataFromClient = System.Text.Encoding.ASCII.GetString (bytesFrom);
dataFromClient = dataFromClient.Substring (0, dataFromClient.IndexOf ("$"));
Debug.Log (" >> Data from Server - " + dataFromClient);
tempMesg = dataFromClient;
string serverResponse = "Last Message from Server" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes (serverResponse);
networkStream.Write (sendBytes, 0, sendBytes.Length);
networkStream.Flush ();
Debug.Log (" >> " + serverResponse);
} catch (Exception ex) {
Debug.Log ("Exception error:" + ex.ToString ());
oThread.Abort ();
oThread.Join ();
}
// Thread.Sleep (500);
}
}
}
Unity is not Thread safe, so they decided to make it impossible to call their API from another Thread by adding a mechanism to throw an exception when its API is used from another Thread.
This question has been asked so many times, but there have been no proper solution/answer to any of them. The answers are usually "use a plugin" or do something not thread-safe. Hopefully, this will be the last one.
The solution you will usually see on Stackoverflow or Unity's forum website is to simply use a boolean variable to let the main thread know that you need to execute code in the main Thread. This is not right as it is not thread-safe and does not give you control to provide which function to call. What if you have multiple Threads that need to notify the main thread?
Another solution you will see is to use a coroutine instead of a Thread. This does not work. Using coroutine for sockets will not change anything. You will still end up with your freezing problems. You must stick with your Thread code or use Async.
One of the proper ways to do this is to create a collection such as List. When you need something to be executed in the main Thread, call a function that stores the code to execute in an Action. Copy that List of Action to a local List of Action then execute the code from the local Action in that List then clear that List. This prevents other Threads from having to wait for it to finish executing.
You also need to add a volatile boolean to notify the Update function that there is code waiting in the List to be executed. When copying the List to a local List, that should be wrapped around the lock keyword to prevent another Thread from writing to it.
A script that performs what I mentioned above:
UnityThread Script:
#define ENABLE_UPDATE_FUNCTION_CALLBACK
#define ENABLE_LATEUPDATE_FUNCTION_CALLBACK
#define ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class UnityThread : MonoBehaviour
{
//our (singleton) instance
private static UnityThread instance = null;
////////////////////////////////////////////////UPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueUpdateFunc then executed from there
private static List<System.Action> actionQueuesUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesUpdateFunc to be executed
List<System.Action> actionCopiedQueueUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteUpdateFunc = true;
////////////////////////////////////////////////LATEUPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueLateUpdateFunc then executed from there
private static List<System.Action> actionQueuesLateUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesLateUpdateFunc to be executed
List<System.Action> actionCopiedQueueLateUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteLateUpdateFunc = true;
////////////////////////////////////////////////FIXEDUPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueFixedUpdateFunc then executed from there
private static List<System.Action> actionQueuesFixedUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesFixedUpdateFunc to be executed
List<System.Action> actionCopiedQueueFixedUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteFixedUpdateFunc = true;
//Used to initialize UnityThread. Call once before any function here
public static void initUnityThread(bool visible = false)
{
if (instance != null)
{
return;
}
if (Application.isPlaying)
{
// add an invisible game object to the scene
GameObject obj = new GameObject("MainThreadExecuter");
if (!visible)
{
obj.hideFlags = HideFlags.HideAndDontSave;
}
DontDestroyOnLoad(obj);
instance = obj.AddComponent<UnityThread>();
}
}
public void Awake()
{
DontDestroyOnLoad(gameObject);
}
//////////////////////////////////////////////COROUTINE IMPL//////////////////////////////////////////////////////
#if (ENABLE_UPDATE_FUNCTION_CALLBACK)
public static void executeCoroutine(IEnumerator action)
{
if (instance != null)
{
executeInUpdate(() => instance.StartCoroutine(action));
}
}
////////////////////////////////////////////UPDATE IMPL////////////////////////////////////////////////////
public static void executeInUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesUpdateFunc)
{
actionQueuesUpdateFunc.Add(action);
noActionQueueToExecuteUpdateFunc = false;
}
}
public void Update()
{
if (noActionQueueToExecuteUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueUpdateFunc queue
actionCopiedQueueUpdateFunc.Clear();
lock (actionQueuesUpdateFunc)
{
//Copy actionQueuesUpdateFunc to the actionCopiedQueueUpdateFunc variable
actionCopiedQueueUpdateFunc.AddRange(actionQueuesUpdateFunc);
//Now clear the actionQueuesUpdateFunc since we've done copying it
actionQueuesUpdateFunc.Clear();
noActionQueueToExecuteUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueUpdateFunc
for (int i = 0; i < actionCopiedQueueUpdateFunc.Count; i++)
{
actionCopiedQueueUpdateFunc[i].Invoke();
}
}
#endif
////////////////////////////////////////////LATEUPDATE IMPL////////////////////////////////////////////////////
#if (ENABLE_LATEUPDATE_FUNCTION_CALLBACK)
public static void executeInLateUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesLateUpdateFunc)
{
actionQueuesLateUpdateFunc.Add(action);
noActionQueueToExecuteLateUpdateFunc = false;
}
}
public void LateUpdate()
{
if (noActionQueueToExecuteLateUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueLateUpdateFunc queue
actionCopiedQueueLateUpdateFunc.Clear();
lock (actionQueuesLateUpdateFunc)
{
//Copy actionQueuesLateUpdateFunc to the actionCopiedQueueLateUpdateFunc variable
actionCopiedQueueLateUpdateFunc.AddRange(actionQueuesLateUpdateFunc);
//Now clear the actionQueuesLateUpdateFunc since we've done copying it
actionQueuesLateUpdateFunc.Clear();
noActionQueueToExecuteLateUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueLateUpdateFunc
for (int i = 0; i < actionCopiedQueueLateUpdateFunc.Count; i++)
{
actionCopiedQueueLateUpdateFunc[i].Invoke();
}
}
#endif
////////////////////////////////////////////FIXEDUPDATE IMPL//////////////////////////////////////////////////
#if (ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK)
public static void executeInFixedUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesFixedUpdateFunc)
{
actionQueuesFixedUpdateFunc.Add(action);
noActionQueueToExecuteFixedUpdateFunc = false;
}
}
public void FixedUpdate()
{
if (noActionQueueToExecuteFixedUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueFixedUpdateFunc queue
actionCopiedQueueFixedUpdateFunc.Clear();
lock (actionQueuesFixedUpdateFunc)
{
//Copy actionQueuesFixedUpdateFunc to the actionCopiedQueueFixedUpdateFunc variable
actionCopiedQueueFixedUpdateFunc.AddRange(actionQueuesFixedUpdateFunc);
//Now clear the actionQueuesFixedUpdateFunc since we've done copying it
actionQueuesFixedUpdateFunc.Clear();
noActionQueueToExecuteFixedUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueFixedUpdateFunc
for (int i = 0; i < actionCopiedQueueFixedUpdateFunc.Count; i++)
{
actionCopiedQueueFixedUpdateFunc[i].Invoke();
}
}
#endif
public void OnDisable()
{
if (instance == this)
{
instance = null;
}
}
}
USAGE:
This implementation allows you to call functions in the 3 most used Unity functions: Update, LateUpdate and FixedUpdate functions. This also allows you call run a coroutine function in the main Thread. It can be extended to be able to call functions in other Unity callback functions such as OnPreRender and OnPostRender.
1.First, initialize it from the Awake() function.
void Awake()
{
UnityThread.initUnityThread();
}
2.To execute a code in the main Thread from another Thread:
UnityThread.executeInUpdate(() =>
{
transform.Rotate(new Vector3(0f, 90f, 0f));
});
This will rotate the current Object the scipt is attached to, to 90 deg. You can now use Unity API(transform.Rotate) in another Thread.
3.To call a function in the main Thread from another Thread:
Action rot = Rotate;
UnityThread.executeInUpdate(rot);
void Rotate()
{
transform.Rotate(new Vector3(0f, 90f, 0f));
}
The #2 and #3 samples executes in the Update function.
4.To execute a code in the LateUpdate function from another Thread:
Example of this is a camera tracking code.
UnityThread.executeInLateUpdate(()=>
{
//Your code camera moving code
});
5.To execute a code in the FixedUpdate function from another Thread:
Example of this when doing physics stuff such as adding force to Rigidbody.
UnityThread.executeInFixedUpdate(()=>
{
//Your code physics code
});
6.To Start a coroutine function in the main Thread from another Thread:
UnityThread.executeCoroutine(myCoroutine());
IEnumerator myCoroutine()
{
Debug.Log("Hello");
yield return new WaitForSeconds(2f);
Debug.Log("Test");
}
Finally, if you don't need to execute anything in the LateUpdate and FixedUpdate functions, you should comment both lines of this code below:
//#define ENABLE_LATEUPDATE_FUNCTION_CALLBACK
//#define ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK
This will increase performance.
I have been using this solution to this problem. Create a script with this code and attach it to a Game Object:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using UnityEngine;
public class ExecuteOnMainThread : MonoBehaviour {
public static readonly ConcurrentQueue<Action> RunOnMainThread = new ConcurrentQueue<Action>();
void Update()
{
if(!RunOnMainThread.IsEmpty)
{
while(RunOnMainThread.TryDequeue(out var action))
{
action?.Invoke();
}
}
}
}
Then when you need to call something on the main thread and access the Unity API from any other function in your application:
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
// Code here will be called in the main thread...
});
Much of the writing about threads in Unity is incorrect.
How so?
Unity is, of course, totally frame-based.
When you work in a frame-based system, threading issues are completely different.
Threading issues on a frame-based system are completely different. (In fact, often much easier to deal with.)
Let's say you have a Unity thermometer display that shows some value
Thermo.cs
So it will have a function which is called in Update, like
func void ShowThermoValue(float fraction) {
display code to show the current thermometer value
}
Recall that the "Update" function in Unity simply means "run this once each frame".
That only runs once per frame, and that's that.
(Naturally, it runs only on the "main thread". There's nothing else in Unity! There's just ... "the Unity thread"!)
Somewhere else, perhaps in "IncomingData.cs", you will have a function which handles the concept "a new value has arrived":
[MonoPInvokeCallback(typeof(ipDel))]
public static void NewValueArrives(float f) {
... ???
}
Note that, of course, that is a class function! What else can it be?
You can't "reach in to" a normal Unity function. (Such as ShowThermoValue.) That would be meaningless - it's just a function which runs once each frame.Footnote 1
Let's say: values arrive very frequently and irregularly.
Image you have some sort of scientific devices (perhaps IR thermometers) connected connected to a rack of PCs
Those electronic devices deliver new "temperature" values very often. Let's say dozens of times per frame.
So, "NewValueArrives" is being called 100s of times a second.
So what do you do with the values?
It could not be simpler.
From the arriving-values thread, all you do is ................. wait for it ............. set a variable in the component!!
WTF? All you do is set a variable? That's it? How can it be that simple?
This is one of those unusual situations:
Much of the writing on threads in Unity is, simply, completely hopeless.
Surprisingly, the actual approach is extremely simple.
It's so simple you may think you are doing something wrong!!
So have the variable ...
[System.Nonserialized] public float latestValue;
Set it from the "arriving thread" ...
[MonoPInvokeCallback(typeof(ipDel))]
public static void NewValueArrives(float f) {
ThisScript.runningInstance.latestValue = f; // done
}
Honestly that's it.
Essentially, to be the world's greatest expert at "threading in Unity" - which is, obviously, frame-based - there's nothing more to do than the above.
And whenever ShowThermoValue is called each frame ...................... simply display that value!
Really, that's it!
[System.Nonserialized] public float latestValue;
func void ShowThermoValue() { // note NO arguments here!
display code, draws a thermometer
thermo height = latestValue
}
You're simply displaying the "latest" value.
latestValue may have been set once, twice, ten times, or a hundred times that frame ............ but, you simply display whatever is the value when ShowThermoValue runs that frame!
What else could you display?
The thermometer is updating at 60fps on-screen so you display the latest value. Footnote 2
It's actually that easy. It's just that easy. Surprising but true.
#(Critical aside - don't forget that vector3, etc, are NOT Atomic in Unity/C#)
As user #dymanoid has pointed out (read the important discussion below) it's critical to remember that while float is atomic in the Unity/C# milieu, anything else (say, Vector3 etc) IS NOT ATOMIC. Typically (as in the example here) you only pass floats around from calculations from, say, native plugins, thermometers etc. But it's essential to be aware that vectors and so on are NOT atomic.
Sometimes experienced threading programmers get in a knot with a frame-based system, because: in a frame based system most of the problems caused by racetrack and locking issues ... do not exist conceptually.
In a frame-based system, any game items should simply be displaying or behaving based on some "current value," which is set somewhere. If you have info arriving from other threads, just set those values - you're done.
You can not meaningfully "talk to the main thread" in Unity because that main thread ............. is frame-based!
Most locking, blocking and racetrack issues are non-existent in the frame-based paradigm because: if you set latestValue ten times, a million times, a billion times, in one particular frame .. what can you do? .. you can only display one value during that frame!
Think of an old-fashioned plastic film. You literally just have ...... a frame, and that's it. If you set latestValue a trillion times in one particular frame, ShowThermoValue will simply display (for that 60th of a second) the one value it grabs when it is run.
All you do is: leave information somewhere, which, the frame-paradigm system will utilize during that frame if it wants to.
That's it in a nutshell.
Thus, most "threading issues" disappear in Unity.
All you can do from
other calculation threads or
from plugin threads,
is just "drop-off values" which the game may use.
That's it!
Let's consider the question title...
How do you "... call a function in the main Thread"
This is completely meaningless. The "functions" in Unity are simply functions which the frame engine runs once per frame.
You can't "call" anything in Unity. The frame engine runs a number of things (many things) once per frame.
Note that indeed threads are totally irrelevant. If Unity ran with a billion threads, or with quantum computing, it would have no bearing on anything.
You can't "call a function" in a frame-based system.
Fortunately, the approach to take is dead simple, you just set values, which the frame-based functions can look at when they want! It's really that easy.
Footnotes
1 How could you? As a thought experiment, forget about the issue that you're on a different thread. ShowThermoValue is run once a frame by the frame engine. You can't "call" it in any meaningful way. Unlike in normal OO software, you cannot, say, instantiate an instance of the class (a Component?? meaningless) and run that function - that is completely meaningless.
In "normal" threaded programming, threads can talk back and fore and so on, and in doing so you have concerns about locking, racetrack and so on. But that is all meaningless in an ECS, frame-based, system. There is nothing to "talk to".
Let's say that Unity was in fact multithreaded!!!! So the Unity guys have all of the engine running in a multithreaded manner. It wouldn't make any difference - you can not get "in to" ShowThermoValue in any meaningful way! It's a Component which the frame engine runs once a frame and that's that.
So NewValueArrives is not anywhere - it's a class function!
Let's answer the question in the headline:
"Use Unity API from another Thread or call a function in the main Thread?"
The concept is >> completely meaningless <<. Unity (like all game engines) is frame-based. There's no concept of "calling" a function on the main thread. To make an analogy: it would be like a cinematographer in the celluloid-film era asking how to "move" something actually on one of the frames.
Of course that is meaningless. All you can do is change something for the next photo, the next frame.
2 I refer to the "arriving-values thread" ... in fact! NewValueArrives may, or may not, run on the main thread!!!! It may run on the thread of the plugin, or on some other thread! It may actually be completely single-threaded by the time you deal with the NewValueArrives call! It just doesn't matter! What you do, and all you can do, in a frame-based paradigm, is, "leave laying around" information which Components such as ShowThermoValue, may use, as, they see fit.
Another solution to run code on the main thread, but without requiring a game object and MonoBehavior, is to use SynchronizationContext:
// On main thread, during initialization:
var syncContext = System.Threading.SynchronizationContext.Current;
// On your worker thread
syncContext.Post(_ =>
{
// This code here will run on the main thread
Debug.Log("Hello from main thread!");
}, null);
Use UniRx's multithreading pattern, UniTask and RxSocket together.
[SerializeField] private Text m_Text;
async UniTaskVoid Connect() {
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 12345);
// Create a socket client by connecting to the server at the IPEndPoint.
// See the UniRx Async tooling to use await
IRxSocketClient client = await endPoint.ConnectRxSocketClientAsync();
client.ReceiveObservable
.ToStrings()
.ObserveOnMainThread()
.Subscribe(onNext: message =>
{
m_Text.text = message;
}).AddTo(this);
// Send a message to the server.
client.Send("Hello!".ToByteArray());
}
My problem is I try to use Unity socket to implement something. Each time, when I get a new message I need to update it to the updattext (it is a Unity Text). However, When I do the following code, the void update does not calling every time.
The reason for I do not include updatetext.GetComponent<Text>().text = "From server: "+tempMesg;in the void getInformation is this function is in the thread, when I include that in getInformation() it will come with an error:
getcomponentfastpath can only be called from the main thread
I think the problem is I don't know how to run the main thread and the child thread in C# together? Or there maybe other problems.
Here is my code:
using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;
public class Client : MonoBehaviour {
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
private Thread oThread;
// for UI update
public GameObject updatetext;
String tempMesg = "Waiting...";
// Use this for initialization
void Start () {
updatetext.GetComponent<Text>().text = "Waiting...";
clientSocket.Connect("10.132.198.29", 8888);
oThread = new Thread (new ThreadStart (getInformation));
oThread.Start ();
Debug.Log ("Running the client");
}
// Update is called once per frame
void Update () {
updatetext.GetComponent<Text>().text = "From server: "+tempMesg;
Debug.Log (tempMesg);
}
void getInformation(){
while (true) {
try {
NetworkStream networkStream = clientSocket.GetStream ();
byte[] bytesFrom = new byte[10025];
networkStream.Read (bytesFrom, 0, (int)bytesFrom.Length);
string dataFromClient = System.Text.Encoding.ASCII.GetString (bytesFrom);
dataFromClient = dataFromClient.Substring (0, dataFromClient.IndexOf ("$"));
Debug.Log (" >> Data from Server - " + dataFromClient);
tempMesg = dataFromClient;
string serverResponse = "Last Message from Server" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes (serverResponse);
networkStream.Write (sendBytes, 0, sendBytes.Length);
networkStream.Flush ();
Debug.Log (" >> " + serverResponse);
} catch (Exception ex) {
Debug.Log ("Exception error:" + ex.ToString ());
oThread.Abort ();
oThread.Join ();
}
// Thread.Sleep (500);
}
}
}
Unity is not Thread safe, so they decided to make it impossible to call their API from another Thread by adding a mechanism to throw an exception when its API is used from another Thread.
This question has been asked so many times, but there have been no proper solution/answer to any of them. The answers are usually "use a plugin" or do something not thread-safe. Hopefully, this will be the last one.
The solution you will usually see on Stackoverflow or Unity's forum website is to simply use a boolean variable to let the main thread know that you need to execute code in the main Thread. This is not right as it is not thread-safe and does not give you control to provide which function to call. What if you have multiple Threads that need to notify the main thread?
Another solution you will see is to use a coroutine instead of a Thread. This does not work. Using coroutine for sockets will not change anything. You will still end up with your freezing problems. You must stick with your Thread code or use Async.
One of the proper ways to do this is to create a collection such as List. When you need something to be executed in the main Thread, call a function that stores the code to execute in an Action. Copy that List of Action to a local List of Action then execute the code from the local Action in that List then clear that List. This prevents other Threads from having to wait for it to finish executing.
You also need to add a volatile boolean to notify the Update function that there is code waiting in the List to be executed. When copying the List to a local List, that should be wrapped around the lock keyword to prevent another Thread from writing to it.
A script that performs what I mentioned above:
UnityThread Script:
#define ENABLE_UPDATE_FUNCTION_CALLBACK
#define ENABLE_LATEUPDATE_FUNCTION_CALLBACK
#define ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class UnityThread : MonoBehaviour
{
//our (singleton) instance
private static UnityThread instance = null;
////////////////////////////////////////////////UPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueUpdateFunc then executed from there
private static List<System.Action> actionQueuesUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesUpdateFunc to be executed
List<System.Action> actionCopiedQueueUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteUpdateFunc = true;
////////////////////////////////////////////////LATEUPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueLateUpdateFunc then executed from there
private static List<System.Action> actionQueuesLateUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesLateUpdateFunc to be executed
List<System.Action> actionCopiedQueueLateUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteLateUpdateFunc = true;
////////////////////////////////////////////////FIXEDUPDATE IMPL////////////////////////////////////////////////////////
//Holds actions received from another Thread. Will be coped to actionCopiedQueueFixedUpdateFunc then executed from there
private static List<System.Action> actionQueuesFixedUpdateFunc = new List<Action>();
//holds Actions copied from actionQueuesFixedUpdateFunc to be executed
List<System.Action> actionCopiedQueueFixedUpdateFunc = new List<System.Action>();
// Used to know if whe have new Action function to execute. This prevents the use of the lock keyword every frame
private volatile static bool noActionQueueToExecuteFixedUpdateFunc = true;
//Used to initialize UnityThread. Call once before any function here
public static void initUnityThread(bool visible = false)
{
if (instance != null)
{
return;
}
if (Application.isPlaying)
{
// add an invisible game object to the scene
GameObject obj = new GameObject("MainThreadExecuter");
if (!visible)
{
obj.hideFlags = HideFlags.HideAndDontSave;
}
DontDestroyOnLoad(obj);
instance = obj.AddComponent<UnityThread>();
}
}
public void Awake()
{
DontDestroyOnLoad(gameObject);
}
//////////////////////////////////////////////COROUTINE IMPL//////////////////////////////////////////////////////
#if (ENABLE_UPDATE_FUNCTION_CALLBACK)
public static void executeCoroutine(IEnumerator action)
{
if (instance != null)
{
executeInUpdate(() => instance.StartCoroutine(action));
}
}
////////////////////////////////////////////UPDATE IMPL////////////////////////////////////////////////////
public static void executeInUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesUpdateFunc)
{
actionQueuesUpdateFunc.Add(action);
noActionQueueToExecuteUpdateFunc = false;
}
}
public void Update()
{
if (noActionQueueToExecuteUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueUpdateFunc queue
actionCopiedQueueUpdateFunc.Clear();
lock (actionQueuesUpdateFunc)
{
//Copy actionQueuesUpdateFunc to the actionCopiedQueueUpdateFunc variable
actionCopiedQueueUpdateFunc.AddRange(actionQueuesUpdateFunc);
//Now clear the actionQueuesUpdateFunc since we've done copying it
actionQueuesUpdateFunc.Clear();
noActionQueueToExecuteUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueUpdateFunc
for (int i = 0; i < actionCopiedQueueUpdateFunc.Count; i++)
{
actionCopiedQueueUpdateFunc[i].Invoke();
}
}
#endif
////////////////////////////////////////////LATEUPDATE IMPL////////////////////////////////////////////////////
#if (ENABLE_LATEUPDATE_FUNCTION_CALLBACK)
public static void executeInLateUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesLateUpdateFunc)
{
actionQueuesLateUpdateFunc.Add(action);
noActionQueueToExecuteLateUpdateFunc = false;
}
}
public void LateUpdate()
{
if (noActionQueueToExecuteLateUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueLateUpdateFunc queue
actionCopiedQueueLateUpdateFunc.Clear();
lock (actionQueuesLateUpdateFunc)
{
//Copy actionQueuesLateUpdateFunc to the actionCopiedQueueLateUpdateFunc variable
actionCopiedQueueLateUpdateFunc.AddRange(actionQueuesLateUpdateFunc);
//Now clear the actionQueuesLateUpdateFunc since we've done copying it
actionQueuesLateUpdateFunc.Clear();
noActionQueueToExecuteLateUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueLateUpdateFunc
for (int i = 0; i < actionCopiedQueueLateUpdateFunc.Count; i++)
{
actionCopiedQueueLateUpdateFunc[i].Invoke();
}
}
#endif
////////////////////////////////////////////FIXEDUPDATE IMPL//////////////////////////////////////////////////
#if (ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK)
public static void executeInFixedUpdate(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
lock (actionQueuesFixedUpdateFunc)
{
actionQueuesFixedUpdateFunc.Add(action);
noActionQueueToExecuteFixedUpdateFunc = false;
}
}
public void FixedUpdate()
{
if (noActionQueueToExecuteFixedUpdateFunc)
{
return;
}
//Clear the old actions from the actionCopiedQueueFixedUpdateFunc queue
actionCopiedQueueFixedUpdateFunc.Clear();
lock (actionQueuesFixedUpdateFunc)
{
//Copy actionQueuesFixedUpdateFunc to the actionCopiedQueueFixedUpdateFunc variable
actionCopiedQueueFixedUpdateFunc.AddRange(actionQueuesFixedUpdateFunc);
//Now clear the actionQueuesFixedUpdateFunc since we've done copying it
actionQueuesFixedUpdateFunc.Clear();
noActionQueueToExecuteFixedUpdateFunc = true;
}
// Loop and execute the functions from the actionCopiedQueueFixedUpdateFunc
for (int i = 0; i < actionCopiedQueueFixedUpdateFunc.Count; i++)
{
actionCopiedQueueFixedUpdateFunc[i].Invoke();
}
}
#endif
public void OnDisable()
{
if (instance == this)
{
instance = null;
}
}
}
USAGE:
This implementation allows you to call functions in the 3 most used Unity functions: Update, LateUpdate and FixedUpdate functions. This also allows you call run a coroutine function in the main Thread. It can be extended to be able to call functions in other Unity callback functions such as OnPreRender and OnPostRender.
1.First, initialize it from the Awake() function.
void Awake()
{
UnityThread.initUnityThread();
}
2.To execute a code in the main Thread from another Thread:
UnityThread.executeInUpdate(() =>
{
transform.Rotate(new Vector3(0f, 90f, 0f));
});
This will rotate the current Object the scipt is attached to, to 90 deg. You can now use Unity API(transform.Rotate) in another Thread.
3.To call a function in the main Thread from another Thread:
Action rot = Rotate;
UnityThread.executeInUpdate(rot);
void Rotate()
{
transform.Rotate(new Vector3(0f, 90f, 0f));
}
The #2 and #3 samples executes in the Update function.
4.To execute a code in the LateUpdate function from another Thread:
Example of this is a camera tracking code.
UnityThread.executeInLateUpdate(()=>
{
//Your code camera moving code
});
5.To execute a code in the FixedUpdate function from another Thread:
Example of this when doing physics stuff such as adding force to Rigidbody.
UnityThread.executeInFixedUpdate(()=>
{
//Your code physics code
});
6.To Start a coroutine function in the main Thread from another Thread:
UnityThread.executeCoroutine(myCoroutine());
IEnumerator myCoroutine()
{
Debug.Log("Hello");
yield return new WaitForSeconds(2f);
Debug.Log("Test");
}
Finally, if you don't need to execute anything in the LateUpdate and FixedUpdate functions, you should comment both lines of this code below:
//#define ENABLE_LATEUPDATE_FUNCTION_CALLBACK
//#define ENABLE_FIXEDUPDATE_FUNCTION_CALLBACK
This will increase performance.
I have been using this solution to this problem. Create a script with this code and attach it to a Game Object:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using UnityEngine;
public class ExecuteOnMainThread : MonoBehaviour {
public static readonly ConcurrentQueue<Action> RunOnMainThread = new ConcurrentQueue<Action>();
void Update()
{
if(!RunOnMainThread.IsEmpty)
{
while(RunOnMainThread.TryDequeue(out var action))
{
action?.Invoke();
}
}
}
}
Then when you need to call something on the main thread and access the Unity API from any other function in your application:
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
// Code here will be called in the main thread...
});
Much of the writing about threads in Unity is incorrect.
How so?
Unity is, of course, totally frame-based.
When you work in a frame-based system, threading issues are completely different.
Threading issues on a frame-based system are completely different. (In fact, often much easier to deal with.)
Let's say you have a Unity thermometer display that shows some value
Thermo.cs
So it will have a function which is called in Update, like
func void ShowThermoValue(float fraction) {
display code to show the current thermometer value
}
Recall that the "Update" function in Unity simply means "run this once each frame".
That only runs once per frame, and that's that.
(Naturally, it runs only on the "main thread". There's nothing else in Unity! There's just ... "the Unity thread"!)
Somewhere else, perhaps in "IncomingData.cs", you will have a function which handles the concept "a new value has arrived":
[MonoPInvokeCallback(typeof(ipDel))]
public static void NewValueArrives(float f) {
... ???
}
Note that, of course, that is a class function! What else can it be?
You can't "reach in to" a normal Unity function. (Such as ShowThermoValue.) That would be meaningless - it's just a function which runs once each frame.Footnote 1
Let's say: values arrive very frequently and irregularly.
Image you have some sort of scientific devices (perhaps IR thermometers) connected connected to a rack of PCs
Those electronic devices deliver new "temperature" values very often. Let's say dozens of times per frame.
So, "NewValueArrives" is being called 100s of times a second.
So what do you do with the values?
It could not be simpler.
From the arriving-values thread, all you do is ................. wait for it ............. set a variable in the component!!
WTF? All you do is set a variable? That's it? How can it be that simple?
This is one of those unusual situations:
Much of the writing on threads in Unity is, simply, completely hopeless.
Surprisingly, the actual approach is extremely simple.
It's so simple you may think you are doing something wrong!!
So have the variable ...
[System.Nonserialized] public float latestValue;
Set it from the "arriving thread" ...
[MonoPInvokeCallback(typeof(ipDel))]
public static void NewValueArrives(float f) {
ThisScript.runningInstance.latestValue = f; // done
}
Honestly that's it.
Essentially, to be the world's greatest expert at "threading in Unity" - which is, obviously, frame-based - there's nothing more to do than the above.
And whenever ShowThermoValue is called each frame ...................... simply display that value!
Really, that's it!
[System.Nonserialized] public float latestValue;
func void ShowThermoValue() { // note NO arguments here!
display code, draws a thermometer
thermo height = latestValue
}
You're simply displaying the "latest" value.
latestValue may have been set once, twice, ten times, or a hundred times that frame ............ but, you simply display whatever is the value when ShowThermoValue runs that frame!
What else could you display?
The thermometer is updating at 60fps on-screen so you display the latest value. Footnote 2
It's actually that easy. It's just that easy. Surprising but true.
#(Critical aside - don't forget that vector3, etc, are NOT Atomic in Unity/C#)
As user #dymanoid has pointed out (read the important discussion below) it's critical to remember that while float is atomic in the Unity/C# milieu, anything else (say, Vector3 etc) IS NOT ATOMIC. Typically (as in the example here) you only pass floats around from calculations from, say, native plugins, thermometers etc. But it's essential to be aware that vectors and so on are NOT atomic.
Sometimes experienced threading programmers get in a knot with a frame-based system, because: in a frame based system most of the problems caused by racetrack and locking issues ... do not exist conceptually.
In a frame-based system, any game items should simply be displaying or behaving based on some "current value," which is set somewhere. If you have info arriving from other threads, just set those values - you're done.
You can not meaningfully "talk to the main thread" in Unity because that main thread ............. is frame-based!
Most locking, blocking and racetrack issues are non-existent in the frame-based paradigm because: if you set latestValue ten times, a million times, a billion times, in one particular frame .. what can you do? .. you can only display one value during that frame!
Think of an old-fashioned plastic film. You literally just have ...... a frame, and that's it. If you set latestValue a trillion times in one particular frame, ShowThermoValue will simply display (for that 60th of a second) the one value it grabs when it is run.
All you do is: leave information somewhere, which, the frame-paradigm system will utilize during that frame if it wants to.
That's it in a nutshell.
Thus, most "threading issues" disappear in Unity.
All you can do from
other calculation threads or
from plugin threads,
is just "drop-off values" which the game may use.
That's it!
Let's consider the question title...
How do you "... call a function in the main Thread"
This is completely meaningless. The "functions" in Unity are simply functions which the frame engine runs once per frame.
You can't "call" anything in Unity. The frame engine runs a number of things (many things) once per frame.
Note that indeed threads are totally irrelevant. If Unity ran with a billion threads, or with quantum computing, it would have no bearing on anything.
You can't "call a function" in a frame-based system.
Fortunately, the approach to take is dead simple, you just set values, which the frame-based functions can look at when they want! It's really that easy.
Footnotes
1 How could you? As a thought experiment, forget about the issue that you're on a different thread. ShowThermoValue is run once a frame by the frame engine. You can't "call" it in any meaningful way. Unlike in normal OO software, you cannot, say, instantiate an instance of the class (a Component?? meaningless) and run that function - that is completely meaningless.
In "normal" threaded programming, threads can talk back and fore and so on, and in doing so you have concerns about locking, racetrack and so on. But that is all meaningless in an ECS, frame-based, system. There is nothing to "talk to".
Let's say that Unity was in fact multithreaded!!!! So the Unity guys have all of the engine running in a multithreaded manner. It wouldn't make any difference - you can not get "in to" ShowThermoValue in any meaningful way! It's a Component which the frame engine runs once a frame and that's that.
So NewValueArrives is not anywhere - it's a class function!
Let's answer the question in the headline:
"Use Unity API from another Thread or call a function in the main Thread?"
The concept is >> completely meaningless <<. Unity (like all game engines) is frame-based. There's no concept of "calling" a function on the main thread. To make an analogy: it would be like a cinematographer in the celluloid-film era asking how to "move" something actually on one of the frames.
Of course that is meaningless. All you can do is change something for the next photo, the next frame.
2 I refer to the "arriving-values thread" ... in fact! NewValueArrives may, or may not, run on the main thread!!!! It may run on the thread of the plugin, or on some other thread! It may actually be completely single-threaded by the time you deal with the NewValueArrives call! It just doesn't matter! What you do, and all you can do, in a frame-based paradigm, is, "leave laying around" information which Components such as ShowThermoValue, may use, as, they see fit.
Another solution to run code on the main thread, but without requiring a game object and MonoBehavior, is to use SynchronizationContext:
// On main thread, during initialization:
var syncContext = System.Threading.SynchronizationContext.Current;
// On your worker thread
syncContext.Post(_ =>
{
// This code here will run on the main thread
Debug.Log("Hello from main thread!");
}, null);
Use UniRx's multithreading pattern, UniTask and RxSocket together.
[SerializeField] private Text m_Text;
async UniTaskVoid Connect() {
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 12345);
// Create a socket client by connecting to the server at the IPEndPoint.
// See the UniRx Async tooling to use await
IRxSocketClient client = await endPoint.ConnectRxSocketClientAsync();
client.ReceiveObservable
.ToStrings()
.ObserveOnMainThread()
.Subscribe(onNext: message =>
{
m_Text.text = message;
}).AddTo(this);
// Send a message to the server.
client.Send("Hello!".ToByteArray());
}
I have a user control that shows a speed in a dial format (An image).
It has a single method: SetSpeed(int speed);
It then makes the dial move to the desired speed, from the last set speed. It does then in incriments. That is, it moves to the new speed.
Problem is, if the car is going 10km/h, and then goes (very quickly) to 100km/h, it takes the dial maybe 2 seconds to reach that speed... (It's not 100% real time - which is realistic .. it moves to the new speed).
But, if, before the dial gets to 100km/h, the person slows to 50km/h, I need to interupt the movement to 100, and start moving to 50. Regardless of the current position (not speed) of the dial, I need to change the 'target speed'.
My control is using a BackgroundWorker to handle the refreshing, and not lock the UI.
So, my call is very basic from the UI:
dial1.SetSpeed(int.Parse(value));
And then the user control does this:
BackgroundWorker bw = new BackgroundWorker();
public void SetSpeed(int speed)
{
while(bw.IsBusy)
{
Thread.Sleep(50);
}
bw.RunWorkerAsync(speed);
}
And the method that does the work:
private void UpdateSpeed(object sender, DoWorkEventArgs e)
{
var oldSpeed = airSpeed;
var newSpeed = (int) e.Argument;
if(oldSpeed <= newSpeed)
{
for (int i = oldSpeed; i < newSpeed; i++)
{
airSpeed++;
this.Invoke(new MethodInvoker(Refresh));
}
}
else
{
for (int i = oldSpeed; i > newSpeed; i--)
{
airSpeed--;
this.Invoke(new MethodInvoker(Refresh));
}
}
airSpeed = newSpeed;
}
It locks when I send it two values in quick succession...
How do I interrupt the thread, if it's running, and change the value?
(Also, I think my code to change the speed is bad - can that be made neater?)
You do not. You handle it in a proper way, with locks, and checking whether the value needs changing. You do NOT interrupt it.
Basically, you need a lock area between SetSpeed and the Refresh method, so that one blocks the other. Then, when you set speed and the thread is currently in a critical area, it simply waits until the update is finished.
And your UpdateSpeed makes no sense - the change (airspeed-- and airspeed++) should be timer driven... you currently change them in a "arbitrary" speed, depending on processor speed. No timing.