I want to take a sprite from a unity sprite atlas and assign it to the texture of the material my mesh is using. I found Sprite.texture but gives me the whole atlas. I just want a single sprite from that atlas
I figured it out.
I get the original UVs for the mesh, set the material texture to the atlas, and change the UVs to draw that specific sprite
public void Init() {
_originalUVs = _meshFilter.mesh.uv;
_originalUVsLength = _originalUVs.Length;
}
public void SetSprite(Sprite sprite) {
// get the rect the sprite uses on the atlas
var spriteRect = sprite.rect;
// convert to UV space (between 0 and 1)
var x = spriteRect.x / sprite.texture.width;
var y = spriteRect.y / sprite.texture.height;
var w = spriteRect.width / sprite.texture.width;
var h = spriteRect.height / sprite.texture.height;
// set uvs for this sprite
var newUVs = new Vector2[_originalUVsLength];
for(var i = 0; i < _originalUVsLength; i++) {
newUVs <em>= new Vector2(x + (w * _originalUVs<em>.x), y + (h * _originalUVs*.y));*</em></em>
* }*
* meshFilter.mesh.uv = newUVs;
material.mainTexture = sprite.texture;*
}