UE4-C++中加载一个蓝图类(二)C++中绑定Blueprint武器

发表于2018-02-26
评论0 4.4k浏览
使用UE4时如何在C++中绑定Blueprint武器,可以editor中编辑好一个武器蓝图资源后,c++中create出这个武器,然后attach到一个人物身上。

思路:
写个c++基类,蓝图继承后编辑成武器或其他装备,然后c++用一个TSubclassOf Weapon1Class;来保存蓝图类,再根据这个这个Weapon1Class类spawn出一个实例,attach到人物身上。

1、写个基类attachment
MyAttachment.h
#pragma once
#include "MyAttachment.generated.h"
UCLASS(Blueprintable)
class USMyAttachment : public USkeletalMeshComponent
{
    GENERATED_UCLASS_BODY()
public:
    USMyAttachment();
    /** Attach point on pawn */
    UPROPERTY(EditDefaultsOnly, Category = Attachment)
        FName AttachPoint; //目标绑定点,提供给蓝图编辑
};

MyAttachment.cpp
#include "MySlate.h"
#include "MyAttachment.h"
USMyAttachment::USMyAttachment(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
}

2、new一个bp继承这个基类


3、在人物的动画蓝图中,添加一个武器绑定点

4、在人物char中用一个成员TSubclassOf来保存class
//h
UCLASS()
class AMyChar : public ACharacter
{
    GENERATED_BODY()
public:
    /** default weapon for the char */
    UFUNCTION(BlueprintCallable, Category = "MyChar")
        void SetWeapon1Class(TSubclassOf<USMyAttachment> InWeapon);
    UPROPERTY(EditAnywhere, Category = "MyChar")
        TSubclassOf<USMyAttachment> Weapon1Class;
    UPROPERTY(EditAnywhere, Category = "MyChar")
        USMyAttachment* Weapon1;//保存生成的蓝图实例
};
//cpp
void AMyChar::SetWeapon1Class(TSubclassOf<USMyAttachment> InWeapon)
{
    Weapon1Class = InWeapon;
}

5、然后在BeginPlay时设置进去这个蓝图class

6、写个测试方法,生成蓝图武器类并绑定到人物身上
void UMyBpFuncLib::TestDressWeapon(AMyChar * _myChar)
{
    if (!_myChar->Weapon1)
    {
        USMyAttachment* MyArmor = NewObject<USMyAttachment>(_myChar, *_myChar->Weapon1Class);
        MyArmor->RegisterComponent();
        MyArmor->AttachTo(_myChar->GetMesh(), MyArmor->AttachPoint);
        _myChar->Weapon1 = MyArmor;
    }
}

7、蓝图掉一下这个测试方法

8、结果:
按8键前:

按8键后:

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引