Id like to add a PNG image to a primitive plane game object using C#
This is simple in the editor as one can simply drag the image onto the plane, but i would like to create the plane dynamically at run-time and then add an image to it.
Can anyone help with this?
string imageString = “C:\testimage.png”);
Material mat = Resources.Load( imageString ) as Material; // <— Should it be material or texture2D?
plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
First, Resources.Load takes a Unix-style path within the assets folder, not a Windows-style path to some file on your hard drive. So, which do you need to do? Get something from your project resources, or get something from a file on disk?
In the former case, move your asset and fix your path, and yes, it should be a Texture2D if what you have in your resources is an image. In the latter case, use standard C# file I/O methods to load the PNG file data, then call Texture2D.LoadImage to convert this into a Texture2D.
Once you have that, you need to get or create a material. A material needs a shader, which you can locate with Shader.Find. Or, if you’re only going to be creating one of these textured planes at a time (or if they all use the same texture), you can just set up a material in your project, and give a reference to that in the script.
Once you have your material reference, you can assign your Texture2D to its mainTexture property, and then assign this material to your plane.
Excellent explanation thanks, based on this I managed to get it working with the code below.
Note the you must create a material in the editor and drag it onto the frontPlane property in the inspector window. Alternatively, you must create a new material at run-time and assign it to frontPlane.
public Material frontPlane;
void Start() {
// Create the Plane
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
// Load the Image from somewhere on disk
var filePath = "C:/MYDATA/MYIMAGE.png";
if (System.IO.File.Exists(filePath))
{
// Image file exists - load bytes into texture
var bytes = System.IO.File.ReadAllBytes(filePath);
var tex = new Texture2D(1, 1);
tex.LoadImage(bytes);
frontPlane.mainTexture = tex;
// Apply to Plane
MeshRenderer mr = plane.GetComponent<MeshRenderer> ();
mr.material = frontPlane;
}
}
Cool! Thank you for following up with your solution, that provides great closure and a handy reference for future googlers who might stumble upon this thread.
One request though: use code tags to make your code more readable. A good way to do that is to click the little “insert” button (between the movie film and the floppy disk) in the editor toolbar.