KITASENJU DESIGN BLOG

memo, html, javascript, unity

Texture2Dに頂点をベイクする

bake vertices to texture2d

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif

public class MeshVertBaker1 : MonoBehaviour
{
    [SerializeField] private Mesh mesh;
    [SerializeField] private int W = 256;
    [SerializeField] private int H = 256;
    
    private Texture2D _tex;
    // Start is called before the first frame update
    void Start()
    {
        
        Debug.Log(mesh.vertexCount);

        int ww = W;
        int hh = H;
        int idx = 0;
        var colors = new Color[ww*hh];

        //random indexをゲットする

        for(int i=0;i<ww;i++){
            for(int j=0;j<hh;j++){
                var v = mesh.vertices[
                    Mathf.FloorToInt(mesh.vertexCount*Random.value*0.9999f)//randomにしてみる
                    //idx%mesh.vertexCount
                ];
                colors[idx] = new Color(v.x,v.y,v.z);                    
                idx++;
            }
        }


        var tt = new Texture2D(ww,hh,TextureFormat.RGBAHalf,0,true);
        tt.SetPixels(0,0,ww,hh,colors);



        //米くする
        #if UNITY_EDITOR
                    var folderName = "BakedAnimationTex";
                    var folderPath = Path.Combine("Assets", folderName);
                    if (!AssetDatabase.IsValidFolder(folderPath))
                        AssetDatabase.CreateFolder("Assets", folderName);

                    var subFolder = name;
                    var subFolderPath = Path.Combine(folderPath, subFolder);
                    if (!AssetDatabase.IsValidFolder(subFolderPath))
                        AssetDatabase.CreateFolder(folderPath, subFolder);

                    AssetDatabase.CreateAsset(tt, Path.Combine(subFolderPath, mesh.name + ".asset"));
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
        #endif

    }

}
"FOOTER"