- Home /
How to render a sprite to a quad?
I select a sprite to render on a quad. I use the following code:
public Sprite m_sprite;
void Awake()
{
m_renderer = GetComponent< MeshRenderer >();
m_mesh = GetComponent< MeshFilter >().mesh;
m_material = m_renderer.material;
Rect spriteRect = m_sprite.textureRect;
spriteRect.x /= m_sprite.texture.width;
spriteRect.width /= m_sprite.texture.width;
spriteRect.y /= m_sprite.texture.height;
spriteRect.height /= m_sprite.texture.height;
// Log.Info("spriteRect {0} num UVs {1}", spriteRect, m_mesh.uv.Length);
// m_mesh.uv[0] = new Vector2(spriteRect.x + 0.0f, spriteRect.y + spriteRect.height);
// m_mesh.uv[1] = new Vector2(spriteRect.x + spriteRect.width, spriteRect.y + spriteRect.height);
// m_mesh.uv[2] = new Vector2(spriteRect.x + 0.0f, spriteRect.y + 0.0f);
// m_mesh.uv[3] = new Vector2(spriteRect.x + spriteRect.width, spriteRect.y + 0.0f);
m_mesh.uv[0] = new Vector2(0.0f, 1.0f);
m_mesh.uv[1] = new Vector2(1.0f, 1.0f);
m_mesh.uv[2] = new Vector2(0.0f, 0.0f);
m_mesh.uv[3] = new Vector2(1.0f, 0.0f);
m_material.mainTexture = m_sprite.texture;
}
MeshRenderer m_renderer;
Mesh m_mesh;
Material m_material;
Update 1: as stevethorne pointed out I need the UVs but the texture is scramble even with the default UVs in the code above. Why is that does the shader or material need certain UVs?
You'll want to get the $$anonymous$$esh of the quad and set the uvs so that it only renders the portion of the texture that you want.
stevethorne: Thank you for your comment. I updated the question.
Answer by robertbu · Jul 18, 2014 at 01:53 PM
I believe that reading from mesh.uv gives you a copy of the array, not a reference to the array, so you need to do it this way:
Vector2[] uvs = m_mesh.uv;
uvs[0] = new Vector2(0.0f, 1.0f);
uvs[1] = new Vector2(1.0f, 1.0f);
uvs[2] = new Vector2(0.0f, 0.0f);
uvs[3] = new Vector2(1.0f, 0.0f);
m_mesh.uv = uvs;
Why is that does the shader or material need certain UVs?
The uvs tell the shader what part of the texture to render for each triangle.
At first glance, it appears that your commented out calculations for uvs should work.
Good hint. Even though a lot more was wrong like the shader, this answer helped me.
Your answer
Follow this Question
Related Questions
Created Material Shows Dark Sprite 1 Answer
How to scale specific part of texture when game object scales? 0 Answers
Create sprite renderer using custom material 2 Answers
Overlay texture on sprite 0 Answers