Skip to content

Instantly share code, notes, and snippets.

@Novack
Forked from SkaillZ/SplatMapToVertColors.cs
Created April 10, 2019 00:36
Show Gist options
  • Select an option

  • Save Novack/7a974de603b1280237aa71fb61819dd7 to your computer and use it in GitHub Desktop.

Select an option

Save Novack/7a974de603b1280237aa71fb61819dd7 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