How can I cast in unreal engine?

I want to know how to do this in the C++. Note the function at the end is a custom function made I c++ and the OverheadWidget variable is UWidgetComponent* type.

I don’t know how to get UserWidgetObject from OverheadWidget variable and then cast it to my Overhead widget and then call the ShowPlayerName function.

@UnrealSolver
@Unreal_Josh

I am not working with C++ unfortunately :frowning:

And for the Casting - depending on where you have created the Widget and where the Reference of it exists - you need to get access to that place and grab the reference of the Widget

The Object is the most important thing, wrong Object = Bad Cast

So instead of casting to the thing you wanna access with some “random” Objects - Cast to the place where it exists

I don’t know where you have it exactly in your Project and I can only advise you in BP but for this - this is a Widget, you can have it in multiple places and it will work, for example:

Create a HUD Class Object, then in Blueprints, almost everywhere - you can “Get HUD” and then Cast to YourCustomHUD

The HUD Code will just contain the Function/Event to create the Widget, eventually show it on the Screen if necessary and create a Reference - basically a Variable with type of ‘WhateverObject Reference’ (f.ex. a BP Object or Widget Reference)

It can also be in your custom Player Controller, you simply use a Function/Event to Create the Widget, if necessary Add to Viewport/Screen and create a Reference

Then anywhere from a Blueprint you ‘Get Player Controller’ and Cast To MyCustomPlayerController to get the Widget Reference out of it and use whatever it offers as Functions, Events, Variables etc.

Same about Pawn to get Player Pawn content - ‘Get Player Pawn’ → Cast To MyCustomPlayerPawn → Get WSP_Overhead_Widget

The Widget you create doesn’t have to be visible to exist and work, so you can create it and create the Reference but the Show/Hide will be as separate Functions

And the Cast should be to the place where you actually create the HUD so you can access it easily regardless if it’s in HUD, Player Controller, Player Pawn or Game Instance, Game Mode etc. - you just need the Variable of it (Reference) to get the information you need out of it - like your Show Player Net Role