Best way to compare actors in C++?

Howdy,

If I misunderstood I apologize, but the comparison of actors is the comparison of the pointer to the actor.

For example:

AActor * Ptr = hitResult->GetActor();

(if you where to view the value of Ptr it would be a memory-address, such as “0x00F34C”, this is simply a number representing where the actor is stored in memory).

the this pointer of a actor class is also a pointer, as is any other pointer to an actor.

Note that regardless of type, a pointer is a unique address in memory, that is to say, two different instances of actor objects will have two totally different pointers.
Further, the pointer’s address is not changed by the inheritance of an object, for example:

AMyPlayerClass * Ptr2 = this;
AActor * Ptr3 = Ptr2;
AMyPawnClass * Ptr4 = this;

if(Ptr2 == Ptr3 == Ptr4)
 //This is true, they are all the same object, regardless of inheritance

By this simple logic, I can easily make a comparison between objects with definite certainty!

AActor * ThisPlayer = this;
AActor * Ptr = hitResult->GetActor();
if(ptr == ThisPlayer) TakeSomeAction();
//or in one tine
if(Cast<AActor>(this) == hitResult->GetActor()) TakeSomeAction();

It is worth noting two small things here.
This is not an Unreal mechanism, this is pure C++ and any tutorial on C++ inheritance and pointers will provide you the knowledge you seek.

Secondly, there is absolutely no gaurentee that if an actor is destroyed the memory will not be reused.
For example, if I stored the value of any Ptr variable above, then during my game that object was destroyed, the memory address might be used for another actor, or something totally different.

TL;DR;

An Instance of an Actor is an object, unless you implement something (such as a UUID), the only way to compare the objects would be to compare every property of the Actor.
The Pointer to the Actor however is not the Actor, it is a unique memory-address of where the actor is stored, Compare pointers to get the result you seek.
Many of my students have understood this better if I simply use the analogy of a postal address.
There might be many people with your name in the world, but only you live at your home-address, by the same logic there may be many AActors in the game, but only one exists at a specific memory address.

[Addendum]

If you wish to discover if an object is of a specific type (such as a certain class, you can use IsA, eg:
Ptr1->IsA(AMyPlayerCharacter).

Also, upon re-reading your question I noticed your issue with firing the raytrace from the camera.
I would suggest attaching something to the camera, just in-front of it (such as a USceneComponent), then firing the ray-trace from that.

Hopefully that will help you kōhai!

1 Like