Accessing variable from hit actors

I made a SweepMultiByChannel that hit actors, now I’d like to access a variable from those hit actors, check if they got the variable and if they do the value of the variable. How exatly do we do that ? :thinking:

TArray<AActor*> AActorTEST::SearchTargetsReturnActors()
{
	TArray<FHitResult> HitResults;

	TArray<AActor*> ActorHit;

	const FVector Start = GetActorLocation();
	const FVector End = GetActorLocation();

	const FCollisionShape MyBox = FCollisionShape::MakeBox(FVector(7, 7, 7));

	const FCollisionQueryParams Param(FName(TEXT("TraceParam")), false, this);

	const bool Hit = GetWorld()->SweepMultiByChannel(HitResults, Start, End, FQuat::Identity, ECC_GameTraceChannel1, MyBox, Param);

	DrawDebugBox(GetWorld(), Start, FVector(7, 7, 7), FColor::Purple, true, 0.5, 0, 10);

	if (Hit)
	{
		for (FHitResult const HitResult : HitResults)
		{
			ActorHit.Add(HitResult.GetActor());
		}
	}

	return ActorHit;
}

You need to attempt to cast the actor to the subclass that has the variable, and if it works, access it through the casted pointer.

Typically, this is hard if your variable is defined in blueprint and you’re trying to do it from C++. You generally want to define everything in C++ that you want to access in C++, and only use Blueprint as “decoration” on top of the base C++ classes, if you do C++ development.

More information about casting in Unreal in C++:

By variable I meant an UPROPERTY.
Basically I just want to get a specific UPROPERTY value of an actor that I hit with a trace.

AYourActorClass* YourActorClass =  Cast<AYourActorClass>(HitResult.GetActor());
if (YourActorClass)
    {
        YourVariable = YourActorClass->YourVariable
    }

If the property value is not tied to a specific class, implement an interface for getting the variable in the classes so you can check if the class implements in the interface and then call the interface function for getting the variable.

thx !
Just one more thing : I’ve read that casting in bp is rather expensive, is it the same in c++ ?

I don’t really know about the runtime cost of the operation really.

The one thing about casting is that it makes a hard reference. So it is generally better used when the class that is being cast to, implies the existence of another. Otherwise, using an interface might make more sense.