- Home /
External Resource Folder -- Please Help
Hi, so I have a Resource folder within my project that i can load textures from. but id like the player to be able to load their own textures from an external resource folder (or any folder they choose)
this is my code so far:
void OnGUI ()
{
filelocationinput = GUI.TextField (new Rect (10, 10, 128, 20), filelocationinput);
if (GUI.Button (new Rect (10, 35, 128, 32), "Load!")) {
LoadTexture ();
}
}
void LoadTexture ()
{
Texture2D boxtexture = Resources.Load (filelocationinput) as Texture2D;
Debug.Log ("loaded texture: " + filelocationinput);
renderer.material.mainTexture = boxtexture;
}
as you can see i have a GUI text field which i want the player to type the file location into (for example: "/Desktop/Game/GameDATA/ExtResource/texture.png")
but of course the code i have atm only loads from the compiled resource folder. any help would be much apreciated.
Answer by rutter · Jan 15, 2014 at 11:18 PM
You're probably already aware, but the Resources
class won't be able to do that for you: it only really supports compiled resources that are shipped with your project.
Instead, you can use the WWW class to request a local file (ie: file:///path/to/file/my_texture.jpg
), wait for the "download" to finish, then call LoadImageIntoTexture to convert that file into a texture. The function linked has a decent example.
This opens up a new can of worms, of course. How do you know which folder to search? Can the user select files in some sort of visual browser? Or will you just check their user docs folder for some specific path/name? The System.IO
namespace provides Path
and Directory
classes that may be very helpful, there.
I second @rutter's points. Here is a quick example using your code.
using UnityEngine;
using System.Collections;
public class Bug25c : $$anonymous$$onoBehaviour
{
public Texture texNotFound;
private string filelocationinput = "";
void OnGUI ()
{
filelocationinput = GUI.TextField (new Rect (10, 10, 128, 20), filelocationinput);
if (GUI.Button (new Rect (10, 35, 128, 32), "Load!")) {
StartCoroutine(LoadTexture ());
}
}
IEnumerator LoadTexture ()
{
WWW www = new WWW ("file://"+filelocationinput);;
yield return www;
Texture boxtexture = null;
if (www.error == null && www.texture != null) {
boxtexture = www.texture;
}
else {
boxtexture = texNotFound;
Debug.Log ("Texture not found");
}
renderer.material.mainTexture = boxtexture;
}
}
thanks guys, this has helped a lot :) i didnt realise that using the www would work.. (but i guess thinking back to when i was young doing html shananigans.. with local html pages.. heheh)
thanks again Also if the file cant be found can i just use return null? or idk
@rutter - thanks. I edited the example to a more traditional use of WWW. He did not need the isDone hack.