Finding sprite UV/texture coordinates in Unity.
This page is now maintained at http://toqoz.fyi/unity-sprite-texture-coordinates.html
If you want to do any kind of texture manipulation in games, you’ll need some form of texture coordinates. If you’re in 3D, you can obtain UV coordinates of a particular point on a mesh via raycasting, but there’s no easy way to achieve the same thing for sprite renders.
Luckily, we can calculate these coordinates ourselves.
The approach here is not very complicated, however, there are many edge cases, and the Unity documentation doesn’t exactly make things simple to arrive at a good solution on your own.
Code
Attach this to each sprite:
[RequireComponent(typeof(SpriteRenderer))]
public class CoordinateMap : MonoBehaviour {
private Sprite sprite;
private void Start() {
sprite = GetComponent<SpriteRenderer>().sprite;
}
public Vector2 TextureSpaceCoord(Vector3 worldPos)
...