Hello!
I´m trying to understand how cast<> works…
what is this for?, does it converts types?, if so, what kind of types does it converts?..
Thanks…
Hello!
I´m trying to understand how cast<> works…
what is this for?, does it converts types?, if so, what kind of types does it converts?..
Thanks…
Hello,
To keep it simple:
Casting ‘‘convert’’ the type, if the object is already from the type you want to cast it into.
If it’s not possible to cast it, it will fail and then return a nullptr.
Example:
Look at all the child classes from AActor
http://api.unrealengine.com/INT/API/…chy/index.html
In your world, you have 3 actors.
Something like this:
AActor* MyStaticMeshActor; // AStaticMeshActor* stored inside AActor*
AActor* MyCameraActor; // ACameraActor* stored inside AActor*
AActor* MyCineCameraActor; // ACineCameraActor* stored inside AActor*
So, the code only knows that all of them are AActors.
But you know that they are more than simple AActors because you wrote the code, and you spawned them using the right class.
So, casting is the way to tell the code which is the ‘‘real’’ type of these objects. Otherwise, you only have access to the functions from the AActor’s class and not from AStaticMeshActor’s class even though MyStaticMeshActor is an AStaticMeshActor.
So, if you want to acces something from AStaticMeshActor, you will have to cast it like so:
AStaticMeshActor* MyCastedStaticMeshActor = Cast<AStaticMeshActor>(MyStaticMeshActor);
if (MyCastedStaticMeshActor != nullptr) { // If the cast worked.
MyCastedStaticMeshActor->GetStaticMeshComponent();
}
But, if you tried to cast your cameras into AStaticMeshActor, it would not have work, because cameras are not child of AStaticMeshActor.
Before leaving, I have a last thing for you, casting work with multiple ‘‘layers’’.
Example:
ACameraActor is a child of AActor.
ACineCameraActor is a child of ACameraActor.
So both are AActor, both are ACameraActor, but only one is ACineCameraActor.
So, in that case …
This will work
ACameraActor* MyCastedCameraActor = Cast<ACameraActor>(MyCameraActor);
if (MyCastedCameraActor != nullptr) { // If the cast worked.
// ...
}
This will also work
ACineCameraActor* MyCastedCineCameraActor = Cast<ACineCameraActor>(MyCineCameraActor);
if (MyCastedCineCameraActor != nullptr) { // If the cast worked.
// ...
}
But this will not work
ACineCameraActor* MyCastedCineCameraActor = Cast<ACineCameraActor>(MyCameraActor); // Look at the variable used
And obviously this will not work either
ACineCameraActor* MyCastedCineCameraActor = Cast<ACineCameraActor>(MyStaticMeshActor); // Look at the variable used
If it helps, maybe you can think of it as accessing any sub-species of canidae or something like that
Source: Canidae - Wikipedia
I hope it helped
you helped me to clarify too much, thanks for that!
Fantastic explanation of Casting.
Cheers,
b