Created
March 6, 2023 15:31
-
-
Save reidscarboro/9b4afa605ef0e15a244eace7dffcd1ff 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 System.IO; | |
using ProtoTurtle.BitmapDrawing; | |
using TMPro; | |
using UnityEngine; | |
public class ImageLoader : MonoBehaviour | |
{ | |
public class NewImageEventArgs { public Texture2D Tex2D; public string FilePath; public bool InitialLoad; }; | |
public delegate void NewImageEventHandler(NewImageEventArgs onNewImageEventArgs); | |
public NewImageEventHandler NewImage; | |
public class ImageRemovedEventArgs { public string FilePath; }; | |
public delegate void ImageRemovedEventHandler(ImageRemovedEventArgs onImageRemovedEventArgs); | |
public ImageRemovedEventHandler ImageRemoved; | |
[SerializeField] TextMeshProUGUI _tmp; | |
[SerializeField] private string _imageFolderPath; | |
[SerializeField] private float _loadNextImageCooldown = 1f; | |
private List<string> _loadedImagePaths = new List<string>(); | |
private float _loadNextImageCountdown = 0; | |
private void Start() | |
{ | |
Log($"Looking for images in {_imageFolderPath}"); | |
LoadImages(true); | |
_loadNextImageCountdown = _loadNextImageCooldown; | |
} | |
private void Update() | |
{ | |
_loadNextImageCountdown -= Time.deltaTime; | |
if (_loadNextImageCountdown < 0) | |
{ | |
_loadNextImageCountdown = _loadNextImageCooldown; | |
LoadImages(false); | |
} | |
} | |
private void Log(string s) | |
{ | |
_tmp.text = _tmp.text + "\n" + s; | |
} | |
private void LoadImages(bool loadAll) | |
{ | |
List<string> filePaths = new List<string>(Directory.GetFiles(_imageFolderPath, "*.png")); | |
foreach (string filePath in filePaths) | |
{ | |
if (!_loadedImagePaths.Contains(filePath)) | |
{ | |
_loadedImagePaths.Add(filePath); | |
Log($"Found new image at {filePath}"); | |
byte[] pngBytes = System.IO.File.ReadAllBytes(filePath); | |
Texture2D tex = new Texture2D(2, 2); | |
tex.LoadImage(pngBytes); | |
tex.FloodClear(5, 5); | |
NewImage?.Invoke(new NewImageEventArgs{Tex2D = tex, FilePath = filePath, InitialLoad = loadAll}); | |
if (!loadAll) return; | |
} | |
} | |
List<string> removedImages = new(); | |
foreach (string loadedImagePath in _loadedImagePaths) | |
{ | |
if (!filePaths.Contains(loadedImagePath)) | |
{ | |
removedImages.Add(loadedImagePath); | |
} | |
} | |
foreach (string removedImage in removedImages) | |
{ | |
ImageRemoved?.Invoke(new ImageRemovedEventArgs{FilePath = removedImage}); | |
_loadedImagePaths.Remove(removedImage); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment