KITASENJU DESIGN BLOG

memo, html, javascript, unity

Binding bones only script

How to bind bones only on Unity 骨をバインドする方法

Binding on Unity C# · GitHub

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

public class BindTest : MonoBehaviour
{

    [SerializeField] private Mesh _mesh;
    [SerializeField] SkinnedMeshRenderer _renderer;
    private int NUM = 10;
    // Start is called before the first frame update
    void Start()
    {
        
        //各頂点にウェイトを埋め込む
        BoneWeight[] weights = new BoneWeight[_mesh.vertexCount];
        for(int i=0;i<_mesh.vertexCount;i++){
            
            weights[i].boneIndex0 = Mathf.FloorToInt(_mesh.uv[i].y*9f);//対応するボーンのindexを入れる
            weights[i].weight0 = 1;//その度合い

        }
        _mesh.boneWeights = weights;


        
        Transform[] bones = new Transform[NUM];
        Matrix4x4[] bindPoses = new Matrix4x4[NUM];

        for(int i=0;i<NUM;i++){

            bones[i] = new GameObject("hoge"+i).transform;
            bones[i].parent = i==0 ? transform : bones[i-1];

            bones[i].localRotation = Quaternion.identity;
            bones[i].localPosition = new Vector3(0,(float)i/(float)(NUM-1),0);//meshに対してこの位置でバインドするのでこの位置は重要

            bindPoses[i] = bones[i].worldToLocalMatrix * bones[i].parent.localToWorldMatrix;

        }

        _mesh.bindposes = bindPoses;

        _renderer.bones = bones;
        _renderer.sharedMesh = _mesh;

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

"FOOTER"