How to Get a reference to an Actor in C++

I am struggling with understanding how to do something that seems like it should be easy enough.
The issue is I dont have a good way of getting a reference to an actor that exists in the level.

Problem:
I want my player to be able to control simple motion of an object from the controller.
For example:
The player presses F and a cube in front of him starts to move.

What Ive tried so far
I have a working interface that will begin moving the cube, but it relies on referring to the object from a line trace and HitResult



FHitResult InteractHit = FHitResult(ForceInit);

//Replace GrameTraceChannel3 if it doesnt work
bool bIsHit = GetWorld()->LineTraceSingleByChannel(InteractHit, Start, End, ECC_GameTraceChannel3, TraceParams);

if (bIsHit)
{
if (InteractHit.GetActor()->GetClass()->ImplementsInterface(UResetInterface::StaticClass()))
{
IResetInterface::Execute_ResetMotion(InteractHit.GetActor());
}
}
{

.

I havent been able to find a C++ solution to getting a reference to the object that doesnt require the player to actually be looking at it.
Iā€™d like to get the reference of the cube on BeginPlay and be able to control it with the character.

Ive gone down several rabbit holes so far in trying to call a custom blueprint event and then returning the actor reference, but I cant figure this out successfully.

Can someone enlighten me on what to do on this one?

Thanks,
Stephen

Hello,

I think there are 4 main routes to choose from:
-spawning the cube from code, which would give you a reference of the created object:

-using the ā€˜GetAllActorsOfClassā€™ function which gives you all the instantiated objects of a given class, but that is generally expensive and considered to be an overkill:

-using something similar to line trace, but using a collision shape (box, sphere, etc) as a trigger volume, which gives you a reference of collided objects
https://docs.unrealengine.com/en-US/Engine/Components/Shapes/index.html
https://docs.unrealengine.com/en-US/Programming/Tutorials/Components/1/index.html

-if you have both your ā€˜controllingā€™ class and your cube placed in the level, you can create an ā€˜InstanceEditableā€™ variable on your controller class that can be set to reference another object (your cube) in the scene.

The most optimal solution depends on your use case and your current setup.

1 Like