0

I have a Unity Program that at initialisation loads multiple Gameobjects in the scenes. The Objects where loaded from a file.

I have created a FileWatcher that notifies when a file has changed. Now I like to update my gameobjects with the content of the updated file

public class ProductFolderWatcher : MonoBehaviour {

// Use this for initialization
void Start () {

    var fileSystemWatcher = new FileSystemWatcher();
    fileSystemWatcher.Path = "C:/Users/Bram Sikkens/Desktop/SealifeBestanden/ProductBestanden/";


    fileSystemWatcher.Changed += FileSystemWatcher_Changed;
    fileSystemWatcher.EnableRaisingEvents = true;

}


private static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
    string filename = e.Name;
    Debug.Log(filename + "has changed");
    GameObject coldBeveragesProductContainer = GameObject.Find("ColdBeveragesProductContainer");


}

When I execute the following code I get the error

"Find can only be executed in main thread"

How do I solve this problem?

Programmer
  • 121,791
  • 22
  • 236
  • 328

1 Answers1

0

Is your FileSystemWatcher running operations on another thread?

It looks like it's dispatching it's event from another thread, in which case Find won't work.

However it maybe that the static FileSystemWatcher_Changed should be non static. Try removing that and see if it improves.

Otherwise if your FileSystemWatcher is running on a different thread, an easy fix would be to remove the static from the FileSystemWatcher_Changed method (that may fix it anyway), and make filename variable a class level variable, i.e. private _filename, and move your GameObject.Find code into an update routine, null the filename after the operation you're doing.

If you're operating from a monobehaviour update routine then you're on the main thread - which is where you want to be.

Dean Marcussen
  • 597
  • 4
  • 15