Using a Public Method from a mono From a plugin class on a diffrent thread

HI guys i need help
I have an c# script made in visual Studio ran on a 2nd thread and i want to fire a method/void on the main thread on a different script.

Problem is it wont Find() the object and script.
I can send information into the script from the start of the thread nut not back out ive tired everything i found so far nothing works.

when i instantiate a mono behavior from the C# class it use the new script that way but i still cannot find game objects…

Start Instantiate script on different thread example:

 h = new AsynchronousClient();

        h.name = null;
        while (h.name == null)
        {
        }
        h.StartClient();

Instantiated Visual Studio c# class script example:

GameObject object = Gameobject.Find(gameobject name);
object.getComponent<script>();
object.sendTestdata(string to send);

back to Unity MonoBehaviour example:

public Void sendTestdtata(string i){
console.print(i);
}

You cannot access most Unity objects and data from a thread that is not the main thread. If you want to pass data back into the main thread from a background thread, my go-to method is using a ConcurrentQueue. Something like this:

public class Example : MonoBehaviour {
  ConcurrentQueue<string> toProcess = new ConcurrentQueue<string>();

  void Update() {
    while (toProcess.TryDequeue(out string data)) {
      print("Received data from background thread: " + data);
    }
  }

  public void SendTestData(string data) {
    toProcess.Enqueue(data);
  }
}

Then you just call SendTestData from your background thread.

whast the code you use to find the script and call the method

Either pass a reference to your MonoBehaviour into the thread when you start it, or use a singleton pattern.

1 Like

got it working thanks a lot !

had to assign the script to a variable on the main thread and pass it into the new thread that way. error was can only assign game object scripts from the main thread.

also im using your code thanks

so as i understand this now the strings coming into the queue and then get proccesed and dequeues first in first out right. in this case it wont loose any data after entered into the queue and how fast can it process the queue if it loads up to much will it hinder the performance on the main thread when processing the dequeue in the update method.

Yrs it’s first in first out. Every update, it will process all elements currently in the queue. If this becomes a performance issue you can change that while loop to limit the number of elements it should read in a particular frame. I’m not sure how much processing you plan to do with the data.

Try to do as much processing ss you can in the background thread before passing data into the main thread. Do everything you can do that doesn’t require access to main-thread-only Unity data.