70 lines
2.5 KiB
C#
Raw Normal View History

2025-09-06 17:17:39 +04:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RenameBones : MonoBehaviour
{
public Transform boneToRemove;
[ContextMenu("Remove Bone and Reassign Weights")]
void RemoveBone()
{
if (boneToRemove == null)
{
Debug.LogError("Кістка для видалення не задана!");
return;
}
SkinnedMeshRenderer skinnedMesh = GetComponent<SkinnedMeshRenderer>();
if (skinnedMesh == null)
{
Debug.LogError("SkinnedMeshRenderer не знайдено!");
return;
}
Transform parentBone = boneToRemove.parent;
if (parentBone == null)
{
Debug.LogError("Неможливо видалити кореневу кістку без оновлення rootBone.");
return;
}
List<Transform> bonesList = new List<Transform>(skinnedMesh.bones);
int removeBoneIndex = bonesList.IndexOf(boneToRemove);
if (removeBoneIndex == -1)
{
Debug.LogError("Кістка не знайдена у списку bones.");
return;
}
foreach (Transform child in boneToRemove)
{
child.SetParent(parentBone);
}
bonesList[removeBoneIndex] = parentBone;
skinnedMesh.bones = bonesList.ToArray();
// Оновлюємо rootBone, якщо потрібно
if (skinnedMesh.rootBone == boneToRemove)
{
skinnedMesh.rootBone = parentBone;
}
// Оновлення ваги вертексів
Mesh mesh = skinnedMesh.sharedMesh;
BoneWeight[] boneWeights = mesh.boneWeights;
for (int i = 0; i < boneWeights.Length; i++)
{
if (boneWeights[i].boneIndex0 == removeBoneIndex) boneWeights[i].boneIndex0 = bonesList.IndexOf(parentBone);
if (boneWeights[i].boneIndex1 == removeBoneIndex) boneWeights[i].boneIndex1 = bonesList.IndexOf(parentBone);
if (boneWeights[i].boneIndex2 == removeBoneIndex) boneWeights[i].boneIndex2 = bonesList.IndexOf(parentBone);
if (boneWeights[i].boneIndex3 == removeBoneIndex) boneWeights[i].boneIndex3 = bonesList.IndexOf(parentBone);
}
mesh.boneWeights = boneWeights;
// Видаляємо кістку
DestroyImmediate(boneToRemove.gameObject);
Debug.Log($"Кістка {boneToRemove.name} видалена, вага перенесена на {parentBone.name}.");
}
}