繁体   English   中英

为什么我不能调用 onFire();

[英]Why can't I call onFire();

我正在尝试在我的游戏中实现武器射击!

我的继承链如下所示:

ACharacter -> AMainCharacter

AActor -> 武器 -> ALaserGun

我试图在ALaserGun类中调用一个函数,但由于某种原因Weapon不是ALaserGun类型。 如果我在蓝图中设置 WeaponAtSpawnClass,如何使用SpawnActor<>()生成与 WeaponAtSpawnClass 类型相同的 actor? 现在,我正在生成一个AWeapon演员。 我想生成一个包含OnFire()AWeapon的孩子。 Weapon的类型是储存在WeaponAtSpawnClass的类。

我注意到的一些可能导致问题的事情:

MainCharacter.h 中的Weapon类型为AWeapon*

Main Character.cpp 中的SpawnActor<>()使用AWeapon作为生成类型。

我是否必须将这些语句中的AWeapon更改为其他内容?

这是我的代码:

主字符.h

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "MainCharacter.generated.h"

class AWeapon;

UCLASS()
class TEST_API AMainCharacter : public ACharacter
{
    GENERATED_BODY()

public:
    AWeapon* Weapon;

    UPROPERTY(EditAnywhere)
    TSubclassOf<AWeapon> WeaponAtSpawnClass;

    void OnFire();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public: 
    // Called to bind functionality to input
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

主要角色.cpp

#include "MainCharacter.h"
#include "Weapon.h"

// Called when the game starts or when spawned
void AMainCharacter::BeginPlay()
{
    Super::BeginPlay();
    Weapon = GetWorld()->SpawnActor<AWeapon>(WeaponAtSpawnClass);
}

void AMainCharacter::OnFire()
{
    Weapon->OnFire();
}

// Called to bind functionality to input
void AMainCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);

    PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AMainCharacter::OnFire);
}

武器.h

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Weapon.generated.h"

UCLASS()
class TEST_API AWeapon : public AActor
{
    GENERATED_BODY()

};

Weapon.cpp 中没有代码

激光枪.h

#pragma once

#include "CoreMinimal.h"
#include "Weapon.h"
#include "LaserGun.generated.h"

UCLASS()
class TEST_API ALaserGun : public AWeapon
{
    GENERATED_BODY()

public:

    void OnFire();
};

激光枪.cpp

#include "LaserGun.h"

void ALaserGun::OnFire()
{
    UE_LOG(LogTemp, Warning, TEXT("Gun fired"))
}

AWeapon* Weapon; 声明一个指向任何AWeapon的指针。 编译器怎么知道它指向具有特定方法的类的实例?

当然,您可以开始将WeaponALaserGun ,但这会导致一团糟。 更好的选择是在接口AWeapon声明方法:

UCLASS()
class TEST_API AWeapon : public AActor
{
    GENERATED_BODY()
 public:  
    virtual OnFire() = 0;
};

并且为了良好的风格声明您覆盖该方法:

UCLASS()
class TEST_API ALaserGun : public AWeapon
{
    GENERATED_BODY()

public:
    void OnFire() override;
};

命名当然取决于你,例如,如果不是所有武器都可以开火,命名方法OnAttack或其他名称,然后从OnAttack或类似名称调用OnFire

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM