Download

Cast to hud from an actor in c++??

Hi all, I’m very new to c++ and ue4 but if anyone knows how to cast to the hud from a normal actor in c++, please give me the code to do so.
Thanks

I am assuming that when you say “normal actor” you mean a class that is either an AActor or derives from an AActor. That being said, your cast to AHUD will only be successful if the AActor you’re looking to cast is, in fact, an AHUD or a class that derives from AHUD. Since you’re very new to C++, I’m going to assume that you’re not entirely familiar with inheritance (if that’s not the case, my apologies).

If you take a look at the inheritance hierarchy of the AHUD class here, you’ll see that it goes UObjectBase > UObjectBaseUtility > UObject > AActor > AHUD. So, AHUD inherits from AActor. AActor inherits from UObject. UObject inherits from UObjectBaseUtility. And so on. So an AHUD object is not only considered an AHUD, but it is also considered all the other classes in its inheritance chain. This means that if I had an AHUD object and I wanted to cast DOWN to an AActor, it would always be successful. However, if I had an AActor object and I wanted to cast UP to an AHUD, it may or may not succeed. Why? Because there are also plenty of other classes that also inherit from AActor. APawn, for example, inherits from AActor. So if I have an AActor that is an APawn, it will not successfully cast up into an AHUD.

Now that we have all that out of the way, I’m going to assume that you know that the AActor you want to cast to an AHUD is, in fact, an AHUD. The code to cast it is as follows:


AHUD* MyHUD = Cast<AHUD>(MyActor);

// Check if MyHUD is valid before using it
if (MyHUD)
{
   //Do stuff with MyHUD here
}

I hope this helps.

I understand it all much more now, thanks so much for the help :slight_smile: