agiro
agiro

Reputation: 2080

Unity - mesh from sprite vertices

I'm trying to create a mesh from a sprite's vertices like so:

private Mesh SpriteToMesh(Sprite sprite)
{
    Mesh mesh = new Mesh
    {
        vertices = Array.ConvertAll(sprite.vertices, i => (Vector3)i),
        uv = sprite.uv,
        triangles = Array.ConvertAll(sprite.triangles, i => (int)i)
    };

    return mesh;
}

Problem is, no errors and I get a simple cube, a 3D one.

My sprite is not quadratic, so it does have some resolution to decrease overdraw.

Question is, how to get that mesh out of a sprite?

My reasons for doing this is that I need particle effects around the edges of the sprite to use the mesh as emitter.

Upvotes: 3

Views: 5977

Answers (1)

agiro
agiro

Reputation: 2080

Sod it, found the way and also why I got a mysterious cube.

The way to do this is like so:

private Mesh SpriteToMesh(Sprite sprite)
{
    Mesh mesh = new Mesh();
    mesh.SetVertices(Array.ConvertAll(sprite.vertices, i => (Vector3)i).ToList());
    mesh.SetUVs(0,sprite.uv.ToList());
    mesh.SetTriangles(Array.ConvertAll(sprite.triangles, i => (int)i),0);

    return mesh;
}

And the reason for the cube was quite simple: Along my script I check if the GameObject the script lives on has a MeshFilter with a mesh on it. If so, use that. I used Unity's Standard Assets' particle systems as base to create my own and they left a cube in a MeshFilter component on it.

Always watch out for cube components, lads.

Upvotes: 5

Related Questions