- Home /
This question was
closed Feb 28, 2015 at 07:58 AM by
thornekey for the following reason:
Problem is not reproducible or outdated
Dynamically store images from file path folder
Ive set up my game to be able to change a texture by inputing a file path. How can I make it so that if i put a folder as a file path all the images in that folder are stored in an array of textures?
Comment
Answer by SkaredCreations · Feb 27, 2015 at 10:47 AM
Here is:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class MyClass : InGameScriptCS
{
Texture[] myTexs = new Texture[0];
void Start ()
{
myTexs = GetTexturesInFolder("/Users/myuser/Pictures");
}
Texture[] GetTexturesInFolder (string path)
{
List<Texture> textures = new List<Texture>();
List<string> texExtensions = new List<string>() { ".png", ".jpg", ".jpeg", ".psd", ".tiff", ".dds" };
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
// Skip non-texture files
if (!texExtensions.Contains(Path.GetExtension(file)))
continue;
try
{
Texture2D tex = new Texture2D(1,1);
tex.LoadImage(File.ReadAllBytes(file));
textures.Add(tex);
}
catch
{
}
}
return textures.ToArray();
}
void OnGUI()
{
if (myTexs.Length > 0)
GUI.DrawTexture(new Rect(0, 0, myTexs[0].width, myTexs[0].height), myTexs[0]);
}
}
i had this: it didnt work. i dont know why...
IEnumerator AllImages() {
if (Directory.Exists (pathDir)) {
dirImages.Clear();
string[] dirPaths = Directory.GetFiles(pathDir, "*.jpg", SearchOption.AllDirectories);
if(dirPaths.Length > 0) {
foreach (string i in dirPaths) {
WWW www = new WWW ("file:///" + pathDir);
yield return www;
Texture prevText = null;
if (www.error == null && www.texture != null) {
prevText = www.texture;
}
else {
prevText = textNotFound;
Debug.Log ("Texture not found");
}
prev_2.renderer.material.mainTexture = prevText;
Texture2D newTex = new Texture2D (1,1 );
www.LoadImageIntoTexture(newTex);
dirImages.Add(newTex);
Debug.Log(i.ToString());
}
}
}
}
it says "You are trying to load data from a www stream which had the following error when downloading."
Why "file:///"? I think it should be "file://" if pathDir is an absolute path (don't know if you need also to replace "\" with "/" for Windows platforms, you'll need to try). Also I think you should pass "i" to WWW ins$$anonymous$$d of "pathDir".