Hello everyone! I recently started with unreal C ++ and want to know how I can call a public variable from a character class of an actor, for example: My character shoots and runs out of ammo, I want him to take a box of ammo and get the full charger .
I have read a lot of posts on this topic, but 90% is for BP and 10% I could not understand very well. Thank you very much!
If you want there’s the code:
[SPOILER]
.H
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "AmmoT.generated.h"
UCLASS()
class TDS_API AAmmoT : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AAmmoT();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
//Set a box collider
UPROPERTY(EditAnywhere)
UShapeComponent* boxCollider;
//Generate the function trigger enter
UFUNCTION()
void OnTriggerEnter(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);
};
.CPP
// Fill out your copyright notice in the Description page of Project Settings.
#include "TDS.h"
#include "AmmoT.h"
#include "MyPlayer.h"
// Sets default values
AAmmoT::AAmmoT()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
//Create the box in fact
boxCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxCollider"));
//Attach to the root
RootComponent = boxCollider;
//Generate overlap event for the box(trigger enter)
boxCollider->bGenerateOverlapEvents = true;
//Link trigger function to the box,when the box hit the player OnTriggerEnter will called
boxCollider->OnComponentBeginOverlap.AddDynamic(this, &AAmmoT::OnTriggerEnter);
//Change the scale
//boxCollider->SetRelativeScale3D(variable or scale x,y,z);
}
// Called when the game starts or when spawned
void AAmmoT::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AAmmoT::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
//The function where all code will execute when the player collide with the box
void AAmmoT::OnTriggerEnter(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) {
if (OtherActor->IsA(ACharacter::StaticClass())) {//This condition only afect to the player,only execute the code screen message with the player,the character class(not tested with enemies)
GEngine->AddOnScreenDebugMessage(-1, 15.0, FColor::Yellow, TEXT("Collision"));
}
}
[/SPOILER]