Cannot set sprite color from secondary thread

Hi, i have a sprite whose color is set by a script running on another thread. When the script attempts to set the color of the sprite, I get an exception saying that Behaviour.get_isActiveAndEnabled should be called from the main thread only.

I figured this means that the Sprite.color property uses the aforementioned isActiveAndEnabled property behind the scenes. What I was wondering is if my workaraound(described below) is the best one and does not have any potential side effects (besides concurrent access to the property which i’ll manage through locks).

So, what I’m currently doing is:

  • Have a MonoBehaviour script running on the main thread, listening for set color requests
  • Whenever the thread must set the color of a sprite it sends a message to the MonoBehaviour script and passes both the color and the sprite as the object paramenter by boxing a custom type that I created for this purpose
  • The MonoBehaviour script unboxes the data and sets the color

Thanks in advance for any help.

I found out why: The UnityEngine API is not thread-safe, because of this the developers decided to block it from being used by other threads. Best solution I could think of is Producer-Consumer pattern where a Producer (running on a secondary thread) sends an Action delegate to the Consumer, which will then invoke it when the next Update() call happens (the producer is a MonoBehaviour attached to an empty Game Object).