我试图统一设置FileSystemWatcher,以便在更新文件时需要更改对象的颜色。
代码没有错误,但是结果没有采取任何措施。如果使用无效的Start(),则可以更改对象的颜色。但只有在所需位置发生更改时,我才需要运行代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class ObjColorScript : MonoBehaviour
{
public Color myColor;
public MeshRenderer myRenderer;
// Start is called before the first frame update
void Start()
{
string path = @"B:\";
MonitorDirectory(path);
///// New Added
var fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = @"B:\";
fileSystemWatcher.Changed += FileSystemWatcher_Changed;
fileSystemWatcher.EnableRaisingEvents = true;
}
///// New Added
void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
myRenderer = GetComponent<MeshRenderer>();
myRenderer.material.color = Color.green;
}
// Update is called once per frame
void Update()
{
//myRenderer = GetComponent<MeshRenderer>();
//myRenderer.material.color = Color.green;
}
}
我有一个类似的问题,我想在更改时调用一个方法,但不会被调用。我相信这与在Unity运行循环外调用事件有关吗?
无论如何对我来说,它有助于在更改时设置bool标志并从Update()
内调用实际方法:
using System.IO;
using UnityEngine;
public class MyFileWatcher : MonoBehaviour
{
[SerializeField] private string path;
[SerializeField] private string file;
private bool changed;
private FileSystemWatcher watcher;
private void OnEnable()
{
if (!File.Exists(Path.Combine(path, file)))
{
return;
}
watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.Filter = file;
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastWrite;
// Add event handlers
watcher.Changed += OnChanged;
// Begin watching
watcher.EnableRaisingEvents = true;
}
private void OnDisable()
{
if(watcher != null)
{
watcher.Changed -= OnChanged;
watcher.Dispose();
}
}
private void Update()
{
if (changed)
{
// Do something here…
changed = false;
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
changed = true;
}
}