制作角色属性Comp
添加一个Actorcomp
在.h内添加生命值与减少血量的函数
protected: //只在蓝图内可以编辑,在编辑器界面不能编辑 UPROPERTY(EditDefaultsOnly,BlueprintReadOnly,Category="Attributs") float Health; // Called when the game starts // public: UFUNCTION(BlueprintCallable,Category="Attributs") bool ApplyHealthChange(float Delta); // Called every frame // };
![](https://img-blog.csdnimg.cn/5b990829475e4fee86cd8ea7ccd950ca.png)
在.cpp内绑定变量与添加减少血量的void
USAttributeComponent::USAttributeComponent() { // Health = 100; // ... } bool USAttributeComponent::ApplyHealthChange(float Delta) { Health += Delta; return true; }
![](https://img-blog.csdnimg.cn/32af3b541ed24ca093d14a0857511040.png)
在角色的.h和.cpp内绑定这个actorcomp
.h
//角色属性 UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category="Components") USAttributeComponent * AttributeComp;
![](https://img-blog.csdnimg.cn/cbbbb10ec18748909fee95704e5d07d8.png)
.cpp
//将创建的AttributeComp绑定在角色上 AttributeComp = CreateDefaultSubobject<USAttributeComponent>("AttributeComp");
![](https://img-blog.csdnimg.cn/fbe492b07e684b3c8883de345c2d2d63.png)
修改魔法子弹的.h,添加一个void
UFUNCTION() void OnActorOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
![](https://img-blog.csdnimg.cn/686e71623c06455eb8e605e6033d8371.png)
.cpp
void ASMagicProjectile::OnActorOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if(OtherActor) { //注意是GetComponentByClass不是GetComponentsByClass USAttributeComponent* AttributeComp = Cast<USAttributeComponent>(OtherActor->GetComponentByClass(USAttributeComponent::StaticClass())); if(AttributeComp) { AttributeComp->ApplyHealthChange(-20.0f); Destroy(); } } }
最后修改碰撞选项
![](https://img-blog.csdnimg.cn/fea15b7db70a4efa92c1ac64f8b6a12c.png)
创建一个生命值的UMG
首先添加Canvas Panel,然后添加Horizontal Box,再添加ProgressBar和Text
![](https://img-blog.csdnimg.cn/fdc3785d34cb4bd8b1809feaa57631b3.png)
在ProgressBar的Slot -> Size处改为Fill
![](https://img-blog.csdnimg.cn/c9177ee0492348f7b7f3d989036a4dc8.png)
在Text的Content ->Text处新建一个Binding
![](https://img-blog.csdnimg.cn/64cc87d57535460ca95fa3eb9cb7485e.png)
函数为接受之前创建的AttributeComponent的Float Health值
效果图:
受到子弹攻击会减少HP的数值