I need a Simple and Clear example for how to add a texture (image) to a quad in C#
Every answer to this question that I have found is different. Seems like it should have a straightforward answer. In simple terms... My question is:
I have created a quad entirely in a C# script. I have a .png file in my Resources folder, and I need the code to load it as a texture and show up on the quad. That's it!
What's the simplest way to do this? (with a code example) (no deprecated functions please :)
Thanks! -j
@JeffreyVentrella I changed the color just for testing.
void Start()
{
Texture t = Resources.Load<Texture>("SpriteName") as Texture;
GetComponent<$$anonymous$$eshRenderer>().material.SetTexture("_$$anonymous$$ainTex",t);
GetComponent<$$anonymous$$eshRenderer>().material.color = new Color(1,0,0,1);
}
Thanks, but your example makes no reference to any particular gameObject. I created a quad using...
quad = GameObject.CreatePrimitive( PrimitiveType.Quad );
$$anonymous$$y question is: how do I attach the texture to THAT object? And do I need to add a renderer, material, etc. to that gameObject?
By the way, this is all happening inside of a script called $$anonymous$$ain.cs which I am using to create all my gameObjects. I need to be explicit about what gameObjects I am adding textures to.
Thanks! -j
Just a quick "make sure" - have you assigned valid UV coords to the quad vertices when you generate them?
Thanks @brijs
But...as I responded to the comment above...
I have a $$anonymous$$ain.cs which I am using to create all my gameObjects, including the quad, using...
quad = GameObject.CreatePrimitive( PrimitiveType.Quad );
I can see the quad. But now I need to add the necessary components (renderer? mesh? material?) and then add the texture. I need to be specific that I am adding the texture to THAT gameObject.
Hopefully this puts my question into the right context for the right answer :)
Thanks! -j
Answer by JeffreyVentrella · Jun 20, 2016 at 03:26 PM
OK folks, I came up with my answer by poking around the interwebs (the answers given were too sparse).
I HOPE THIS IS USEFUL for other people with the same question that I had:
I created a Resources folder inside of the Assets folder.
I Created a Material in the Resources folder which I renamed to "Whatever".
I dragged a .png file called "my_image" into the Resources folder.
I added the following code to the Start method:
GameObject quad = GameObject.CreatePrimitive( PrimitiveType.Quad );
Material quadMaterial = (Material)Resources.Load( "Whatever" );
quad.GetComponent().material = quadMaterial;
Texture2D myTexture = Resources.Load( "my_image" ) as Texture2D;
quad.GetComponent().material.mainTexture = myTexture;
Answer by Brijs · Jun 16, 2016 at 10:33 AM
In Monobehaviour attached to quad
1) Load texture
Texture texture = Resources.Load<Texture>("TextureName") as Texture;
2) Now wherever you want to add texture to quad write this
GetComponent<Renderer>().material.mainTexture = texture;