Skip to content

Instantly share code, notes, and snippets.

@facybenbook
Forked from SkaillZ/SplatMapToVertColors.cs
Created April 12, 2019 19:07
Show Gist options
  • Save facybenbook/b08b0af69bb596afdc7d183dc3b904d1 to your computer and use it in GitHub Desktop.
Save facybenbook/b08b0af69bb596afdc7d183dc3b904d1 to your computer and use it in GitHub Desktop.
Copy splat map to vertex colors
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace RoboticWeaselAssault.Gamutmamut.Editor
{
public class EditorTools
{
/// <summary>
/// Copies a splat map into a mesh's vertex colors. A mesh and a texture must be selected simultaneously.
/// Read/write must be enabled in the texture's import settings.
/// </summary>
[MenuItem("Tools/Copy SplatMap to Vertex Colors")]
public static void SplatMapToVertexColors()
{
var mesh = Selection.objects.OfType<Mesh>().FirstOrDefault();
var texture = Selection.objects.OfType<Texture2D>().FirstOrDefault();
if (mesh == null || texture == null)
{
throw new Exception("Please select a mesh and a texture.");
}
var newMesh = CopyMesh(mesh);
var colors = new Color[newMesh.vertexCount];
var uvs = newMesh.uv;
for (var i = 0; i < colors.Length; i++)
{
// Get the texture coordinates
var uv = uvs[i];
// Sample the texture on the given UV position
colors[i] = texture.GetPixelBilinear(uv.x, uv.y);
}
newMesh.colors = colors;
// Show a UI to get the path where the new mesh should be saved
string targetPath = EditorUtility.SaveFilePanel("Save mesh", "Assets/", mesh.name, "asset");
if (targetPath != null)
{
AssetDatabase.CreateAsset(newMesh, FileUtil.GetProjectRelativePath(targetPath));
}
}
private static Mesh CopyMesh(Mesh mesh)
{
return new Mesh
{
vertices = mesh.vertices,
triangles = mesh.triangles,
uv = mesh.uv,
uv2 = mesh.uv2,
normals = mesh.normals,
colors = mesh.colors,
tangents = mesh.tangents
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment