您好,感谢您的回答,但是我提供的代码里构造函数已经标记为可复制。所以可能的问题是您所说的指针为空?
除了使用多播函数,我所能想到的就是属性同步。所以我做了如下更改。
UCLASS()
class MYPROJECT_API ATargetCube : public AActor
{
GENERATED_BODY()
public:
ATargetCube();
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
protected:
virtual void BeginPlay() override;
private:
UPROPERTY(EditDefaultsOnly)
UBoxComponent* BoxComponent;
UPROPERTY(EditDefaultsOnly)
UStaticMeshComponent* BoxMesh;
UPROPERTY(EditDefaultsOnly)
UMaterialInstance* DoublePointsCubeMaterial;
UPROPERTY(ReplicatedUsing = "OnRep_UseDoublePointsCubeMaterial")
bool bUseDoublePointsCubeMaterial = false;
UFUNCTION()
void OnRep_UseDoublePointsCubeMaterial();
};
CPP文件是:
ATargetCube::ATargetCube()
{
PrimaryActorTick.bCanEverTick = false;
bReplicates = true;
BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComponent"));
BoxComponent->SetBoxExtent(FVector(50.f, 50.f, 50.f));
SetRootComponent(BoxComponent);
BoxMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BoxMesh"));
BoxMesh->SetupAttachment(GetRootComponent());
}
void ATargetCube::BeginPlay()
{
Super::BeginPlay();
if (AMyProjectGameMode* GameMode = Cast<AMyProjectGameMode>(UGameplayStatics::GetGameMode(this)))
{
Score = GameMode->GetCubeScore();
if (GameMode->MustSpawnDoublePointsCube() || (GameMode->CanSpawnDoublePointsCube() && FMath::RandBool()))
{
GameMode->AddDoublePointsCubeCount();
bUseDoublePointsCubeMaterial = true;
BoxMesh->SetMaterial(0, DoublePointsCubeMaterial);
}
GameMode->AddCubeCount();
}
else if (bUseDoublePointsCubeMaterial)
{
BoxMesh->SetMaterial(0, DoublePointsCubeMaterial);
}
}
void ATargetCube::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ThisClass, bUseDoublePointsCubeMaterial);
}
void ATargetCube::OnRep_UseDoublePointsCubeMaterial()
{
bUseDoublePointsCubeMaterial = true;
BoxMesh->SetMaterial(0, DoublePointsCubeMaterial);
}
通过这种方式成功实现了我的需求。