- Home /
Loading user custom image.
I'm pretty desperated with this. I'm crafting simple openGL program, where user put his own image inside so i cant put that image into assets. I tried www class and also tried Texture.LoadImage(string path). www class loaded image, texture loaded as well. But the image never appeared at the program and unity just shown white material. This is how the code looks lately:
string path = Application.dataPath;
if (Image == "") {
path = Path.Combine(path, "pink.png");
} else {
path = Path.Combine(path, Image);
}
var shaderText =
"Shader \"Alpha Additive\" {" +
"Properties { _MainText (" +
"\"texture\""+
", 2D) = \"white\" {}}" +
"SubShader {" +
" Tags { \"Queue\" = \"Transparent\" }" +
" Pass {" +
" Blend One One ZWrite Off ColorMask RGB" +
" Material { Diffuse [_Color] Ambient [_Color] }" +
" Lighting On" +
" SetTexture [_Dummy] { combine primary double, primary }" +
" }" +
"}" +
"}";
Texture2D texture = new Texture2D(1,1);
FileStream stream = new FileStream(path, System.IO.FileMode.Open);
BinaryReader reader = new BinaryReader(stream);
byte[] buffer = reader.ReadBytes(10000000);
texture.LoadImage(buffer);
var noteMaterial = new Material(shaderText);
noteMaterial.mainTexture = texture;
MeshRenderer[] NoteRenderer = note.gameObject.GetComponentsInChildren<MeshRenderer>();
NoteRenderer[2].material = noteMaterial;
as i wrote i also tred www class. First thing - at monodevelop it says "yield www;" is not regular command and when i used "yield return www" the unity shouts it is not regular command. Only thing i beg is to have code which will take my picture from app folder and put it on some prefab and im really tired of finding only Resources.Load, and unsuccessfull www class and texture.loadimage(). Well is there anyone who was lucky with doing this? thx.
Answer by robertbu · Feb 21, 2013 at 04:22 PM
The syntax in C# for waiting for load using the WWW clase is "yield return www". Here is a few lines demonstrating a load of a texture using WWW:
public class LoadTexture : MonoBehaviour {
void Update () {
if (Input.GetKeyDown (KeyCode.A))
StartCoroutine (LoadATexture ("file://e://foo.jpg"));
}
IEnumerator LoadATexture(string st) {
WWW www = new WWW(st);
yield return www;
if (www.error == null) {
renderer.material.mainTexture = www.texture;
}
}
}
Well this answer i found many times before and i tried it many times before.
For everyone whose stumbling on this: This answer works but one important thing is to add "file:\\" or "file://" on the beggining.