Hi, I am making a program that views a few products, they are all tied to a parent that you can rotate and you can use a dropdown to change which product is displayed at that moment. I also want a user to be able to add his own texture to a specified directory and the program to load it if it changes.
I made a script that seemd to be working when I only had 3 products, now I added 2 more and It is not working for the new ones. If I start the Corutine when changing the product with the dropdown it loads the texture but I don’t want to do it this way. I want it to load the texture once the product is first displayed and reload when it is changed.
I always have the same product as a starting one, the weird thing is that the new products I added are trying to load the textures before the starting one while they are invisible. I tested that using the debug log.
using System.Collections;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
using System;
public class Change_texture : MonoBehaviour
{
public Material material;
bool changedf = false;
void Start()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
createFileWatcher(path);
Debug.Log("Starting loading image of: " + this.name);
StartCoroutine("LoadImage");
}
// Update is called once per frame
void Update()
{
if (changedf == true)
{
string name = this.name;
StartCoroutine("LoadImage");
Debug.Log(name + " updated");
changedf = false;
}
}
void createFileWatcher(string path)
{
string name = this.name;
string file = path + "/Product_Viewer/" + name + ".png";
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Path.GetDirectoryName(file);
watcher.Filter = Path.GetFileName(file);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
Debug.Log("created watcher of: " + this.name);
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
changedf = true;
}
IEnumerator LoadImage()
{
Debug.Log("entered loading of image of: " + this.name);
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string name = this.name;
string file = path+ "/Product_Viewer/" + name + ".png";
//Debug.Log(file);
using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(file))
{
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log("error loading texture");
Texture backUpTexture = (Texture2D)Resources.Load(name+".png");
material.mainTexture = backUpTexture;
}
else
{
Debug.Log("Loaded: " + name);
var reqTexture = DownloadHandlerTexture.GetContent(req);
material.mainTexture = reqTexture;
}
}
}
}
Thanks to everyone that looks into it ![]()