I know Threading is not supported but...

I’ll do my best to describe this situation.

We have a C# DLL.
We have a C# class that gets consumed to process data. I’ll call this for the lack of a better name, DLLProcessingClass.cs
This class has an event that we subscribe to that gives alerts about the data.

This class has a function that crunches data. It does this by spinning up it’s own internal thread somehow. Not sure how it works, I’ve never seen the code, it’s a black box to me. I just know when I call the function, a thread is started and processes data.

While processing this data in this function and internal thread, when a certain condition exits, the internal functionality will trigger the classes event, thus sending data back in the event object.

So far so good.

So in Unity, I have a script, i’ll call it MyScript.cs that loads up the ProcessingClass and kicks off the processing function.

MyScript subscribes to the event. And when this event handler catches the event, I’m taking the data from the event object and passing that data back to a controlling script which is attached to a game object. So the hierarchy would look like this.

GameObject → ControllingScript → MyScript → DLLProcessingClass

DLLProcessingClass has a function which creates a thread, it triggers an event that’s consumed by MyScript, MyScript turns around and passes that data (via it’s own defined event) back to ControllingScript which subscribes to MyScripts event.

So… Here is the problem.
In my scene I have a UI InputField. Just a simple text box area.
When I try to use the data that has come back up the chain of classes in the GameObject, I’m getting a threading error that states :

get_isPlaying can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene.

I realize that unity is not thread safe. At least from my understanding. So,

You simply need to get the result of the operation done on the worker thread onto the main thread. I usually do this by declaring a variable and setting it (using lock {} if need be) in the event that’s called on the worker thread, and having the MonoBehaviour that needs this data check this variable in the Update() loop (also with lock {}).

Hi Thomas. That is what I had tried without the lock though…
I would grab the data, store it into a local string variable in the “ControllingScript” class… Was not working. Hadn’t considered using lock! I’ll give that a try. Thanks for the tip!!!

Rick

Excellent! Thank you Thomas, that was the ticket! :slight_smile:

1 Like