首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与FileSystemWatcher的统一

与FileSystemWatcher的统一
EN

Stack Overflow用户
提问于 2019-06-20 00:18:36
回答 1查看 524关注 0票数 0

我正在尝试设置一个FileSystemWatcher,当文件更新时,我需要更改对象的颜色。

代码中没有错误,但结果是不执行操作。如果我使用void Start(),我可以改变对象的颜色。但是,只有在所需位置发生更改时,我才需要运行代码。

代码语言:javascript
复制
    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;
    }

}
EN

回答 1

Stack Overflow用户

发布于 2020-06-04 05:39:08

我遇到了一个类似的问题,我想在更改时调用一个方法,但它不会被调用。我相信这与Unity run循环外部调用的事件有关?

无论如何,对我来说,在更改时设置一个布尔标志并从Update()中调用实际的方法是很有帮助的

代码语言:javascript
复制
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;
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56672064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档