1
\$\begingroup\$

So I am still learning C++ but been using it for quite a while. But I have a function which is not working properly (separate question posted here: Calling Client RPC in order to assign a Team value to clients. How to check the Role properly? - Development Discussion / Multiplayer & Networking - Unreal Engine Forums).

I am starting to think the problem MIGHT be about how I cast from the APawn* to APlayerMallet* (which is actually extending ACharacter not APawn).

APlayerMallet* mallet=(APlayerMallet*)gamestate->PlayerArray[i]->GetPawn();

The code compiles and it does find the function in APlayerMallet if I change the IF statement to force it to call the function in APlayerMallet.

I suppose here I am just looking for confirmation that it is ok to do such a cast.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Using a c-style cast like this ((APlayerMallet*)) basically tells the compiler: "I know what I'm doing don't do any checks. Whatever is at GetPawn address, interpret it as a APlayerMallet." Combined with "So I am still learning C++", I think you should try a static cast instead. The compiler will make sure that the type can be correctly cast. Does ACharacter extend APawn? \$\endgroup\$
    – Vaillancourt
    Mar 5 at 2:10
  • 1
    \$\begingroup\$ Also, FWIW, this appears to be a c++ related question more than a game dev question, which are generally off-topic here. \$\endgroup\$
    – Vaillancourt
    Mar 5 at 2:11
  • \$\begingroup\$ Thank you very much for this information. I will try with static cast. I did notice that PlayerArray has a Template function (for convenient casting) which I will also try. Also I thought this question fitted in the grey-area between c++ and gamedev since it was about Unreal specifically but I take onboard what you say about the question topic. Thanks again for helping me \$\endgroup\$
    – DaveGold
    Mar 5 at 3:32
  • \$\begingroup\$ ACharacter is an extended APawn , yes. And indeed APlayerMallet extends ACharacter. I am not sure if that is covered by the casting since the function I had to call to get access to the player was called GetPawn. However at some point in my testing I did indeed call some functions from the APlayerMallet so I think maybe the casting is not the actual problem. Again, thank you for the info about static_cast \$\endgroup\$
    – DaveGold
    Mar 5 at 3:34

1 Answer 1

3
\$\begingroup\$

why not use the UE's Cast function?

APlayerMallet* mallet=(APlayerMallet*)gamestate->PlayerArray[i]->GetPawn();

Becomes:

APawn* ThePawn = gamestate->PlayerArray[i]->GetPawn();
APlayerMallet* mallet= Cast<APlayerMallet>(ThePawn); //returns nullptr if failed
if(!mallet)
{
//return or error handle
}
mallet->DoStuff();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .