Created
May 9, 2019 08:41
-
-
Save kodai100/18e9ca8a5e7e6b6460e60411e2ae7aaf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
using System.IO; | |
using UnityEngine.Networking; | |
using UniRx.Async; | |
public class FileWatcher : MonoBehaviour | |
{ | |
static readonly string watchFolderPath = Application.streamingAssetsPath; | |
[SerializeField] List<Texture> textures = new List<Texture>(); | |
FileSystemWatcher watcher; | |
void Awake() | |
{ | |
Clear(); | |
} | |
void Start() | |
{ | |
watcher = new FileSystemWatcher(); | |
watcher.Path = watchFolderPath; | |
watcher.Filter = "*.jpg"; | |
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite; | |
watcher.IncludeSubdirectories = false; | |
watcher.Created += new FileSystemEventHandler(WatcherChanged); | |
watcher.EnableRaisingEvents = true; | |
} | |
private void OnDestroy() | |
{ | |
if (watcher == null) return; | |
watcher.EnableRaisingEvents = false; | |
watcher.Dispose(); | |
watcher = null; | |
} | |
async void WatcherChanged(System.Object _, FileSystemEventArgs e) | |
{ | |
switch (e.ChangeType) | |
{ | |
case WatcherChangeTypes.Created: | |
Debug.Log($"File created : {e.FullPath}"); | |
var texture = await LoadTextureAsync(e.FullPath); | |
if(texture) | |
textures.Add(texture); | |
break; | |
} | |
} | |
async UniTask<Texture> LoadTextureAsync(string url) | |
{ | |
Debug.Log($"Load start : {url}"); | |
var request = UnityWebRequestTexture.GetTexture($"{url}"); | |
await request.SendWebRequest(); | |
if (request.isNetworkError || request.isHttpError) | |
{ | |
Debug.LogError(request.error); | |
return null; | |
} | |
else | |
{ | |
Texture tex = DownloadHandlerTexture.GetContent(request); | |
Debug.Log($"Loaded : {tex.name}"); | |
return tex; | |
} | |
} | |
public void Clear() | |
{ | |
textures.Clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment