Error9.骨骼网格体动画天坑!
大约 2 分钟
202411/13补 UE5.4BUG已经修复,5.3没试过,5.2是有这个问题的
void UExorcistFunctionLibrary::SetSkeletalMeshAndAnimation(USkeletalMesh* NewMesh, UAnimationAsset* NewAnimation,
float PlayRate, bool bLooping,
USkeletalMeshComponent* TargetMeshComponent)
{
if (TargetMeshComponent)
{
// 设置骨骼网格
TargetMeshComponent->SetSkeletalMesh(NewMesh);
// 播放动画
if (NewAnimation)
{
TargetMeshComponent->PlayAnimation(NewAnimation, bLooping);
TargetMeshComponent->SetPlayRate(PlayRate);
}
}
}
void USkeletalMeshComponent::PlayAnimation(class UAnimationAsset* NewAnimToPlay, bool bLooping)
{
SetAnimationMode(EAnimationMode::AnimationSingleNode);
SetAnimation(NewAnimToPlay);
Play(bLooping);
}
void USkeletalMeshComponent::SetAnimation(UAnimationAsset* NewAnimToPlay)
{
UAnimSingleNodeInstance* SingleNodeInstance = GetSingleNodeInstance();
if (SingleNodeInstance)
{
SingleNodeInstance->SetAnimationAsset(NewAnimToPlay, false);
SingleNodeInstance->SetPlaying(false);
}
else if( AnimScriptInstance != nullptr )
{
UE_LOG(LogAnimation, Warning, TEXT("Currently in Animation Blueprint mode. Please change AnimationMode to Use Animation Asset"));
}
}
一. 动态创建组件
1.使用 NewObject
和 RegisterComponent
:
// 创建 Actor Component
USkeletalMeshComponent* SkeletalMeshComponent = NewObject<USkeletalMeshComponent>(this, USkeletalMeshComponent::StaticClass(), TEXT("SkeletalMeshComponent"));
// 注册组件
SkeletalMeshComponent->RegisterComponent();
2. 使用 AddInstanceComponent
:
USkeletalMeshComponent* SkeletalMeshComponent = AddInstanceComponent(USkeletalMeshComponent::StaticClass(), TEXT("SkeletalMeshComponent"));
SkeletalMeshComponent->SetRelativeTransform(InStruct.SkeletalTransform);
二. 缓存材质,传递材质
// 其中SkeletalMesh为传入的新的骨骼网格物体,请自己判断原始模型上有没有材质
TArray<FSkeletalMaterial> CurrentMats = SkeletalMesh->GetMaterials();
SkeletalMeshComponent->SetSkeletalMesh(SkeletalMesh);
SkeletalMeshComponent->SetMaterials(CurrentMats);
正确的应该是:
TArray<FSkeletalMaterial> CurrentMats = SkeletalMesh->GetMaterials();
if (CurrentMats.Num() > 0)
{
for(int32 i=0;i<CurrentMats.Num();++i)
{
SkeletalMeshComponent->SetMaterial(i,CurrentMats[i].MaterialInterface);
}
}