- Home /
Load image onto a Plane in the editor using C#
I have written a script which, when run in game mode, loads an image onto a plane:
static Texture2D Load(string path){
Texture2D tex = null;
byte[] data;
if (File.Exists(path))
{
data = File.ReadAllBytes(path);
tex = new Texture2D(Screen.width, Screen.height);
tex.LoadImage(data); //..this will auto-resize the texture dimensions.
}
return tex;
}
void Display(GameObject plane, byte[] data){
var texture = new Texture2D(Screen.width, Screen.height);
texture.LoadRawTextureData(data);
texture.Apply();
var the_renderer = plane.GetComponent<Renderer>();
the_renderer.material.mainTexture = texture;
}
Now, rather than have to press play every time, I'd like to have a couple of buttons in the editor which I can press to run my script and load the image onto a plane.
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(ImageUtils))]
public class Buttons : Editor {
public override void OnInspectorGUI()
{
DrawDefaultInspector();
ImageUtils imageUtils = (ImageUtils)target;
if (GUILayout.Button("RunTest"))
{
imageUtils.FullTest(); // reads in image, converts to texture2d and applies to a plane.
}
}
}
This all works fine, apart from when texture.LoadRawTextureData(data);
is called. It throws an exception saying "not enough data provided (will result in overread).".
My images are 500x500, and in-game, the screen size is set to 500x500 standalone...
I know that my problem lies with this line: var texture = new Texture2D(Screen.width, Screen.height);
. I need to know what to set width and height to, but how? The scale of the plane (1, 1, 1) does not work.
If I do use 1, 1, 1 Unity tells me that I should use the_renderer.sharedMaterial.mainTexture = texture;
to avoid color leaking... but when I do that, I just get a colored plane and the shader has been modified...
How can I get my Editor to be the correct size, or better, the image to correctly map to the plane?