我正在尝试设置一个FileSystemWatcher,当文件更新时,我需要更改对象的颜色。
代码中没有错误,但结果是不执行操作。如果我使用void 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;
}
}发布于 2020-06-04 05:39:08
我遇到了一个类似的问题,我想在更改时调用一个方法,但它不会被调用。我相信这与Unity run循环外部调用的事件有关?
无论如何,对我来说,在更改时设置一个布尔标志并从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;
}
}https://stackoverflow.com/questions/56672064
复制相似问题