ObservedTextFile

The ObservedTextFile class allows you to subscribe to changes made to a text file on the file system. When changes are made to the file, subscribers will be notified with the new text and a WatcherChangeTypes value indicating the type of change that occurred (e.g. Changed, Created, Deleted, Renamed).

Note that the Created type is also used when writing all text to the file, i.e. replacing all of its content. Additionally, when the file is moved, the Renamed type will be used.

Usage

To use ObservedTextFile, first create an instance of the class and pass in the path to the text file you want to observe. Then, use the Subscribe method to pass in a callback function that will be called whenever the file is changed. The callback function should accept two arguments: a string representing the new text of the file, and a WatcherChangeTypes enum value representing the type of change that occurred (e.g. Changed, Created, Deleted, or Renamed).

Here is an example of how ObservedTextFile can be used in a Unity MonoBehaviour class:

using System;
using UnityEngine;
using Observed;

public class TextFileObserver : MonoBehaviour
{
    private ObservedTextFile _textFile;

    private void Start()
    {
        _textFile = new ObservedTextFile("test.txt");
        _textFile.Subscribe((text, type) =>
        {
            Debug.Log($"Text file change detected! New text: {text}. 
                Change type: {type}");
        });
    }
}

You can also unsubscribe from file change events by calling the Unsubscribe method and passing the callback function as an argument, or clear all subscribers by calling the ClearSubscriptions method.

Last updated