Download

How to show the mouse cursor at runtime in C++?

Hello,

C++ in Unreal is still unclear for me. I’d like to show the mouse cursor at runtime in C++ and the code seems to be compiled but it doesn’t work in Unreal Editor.
In the default MyCharacter.h I added the code:


UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class APlayerController* MyController;


And in the default MyCharacter.cpp I added (in the constructor) the code:



//I don't know if
MyController = GetWorld()->GetFirstPlayerController(); //either this code should be 
MyController = CreateDefaultSubobject<APlayerController>(TEXT("MyController")); //or this one

//they both can be compiled, but make the UE Editor crash

MyController->bShowMouseCursor = true;
MyController->bEnableClickEvents = true;
MyController->bEnableMouseOverEvents = true;


The problem is that I’m not sure how I should get the character’s controller from my character.

Your character already has a controller, assuming it was spawned correctly. So you can just use GetController() to get it.



APlayerController* PC = GetController();

if (PC)
{
PC->bShowMouseCursor = true; 
PC->bEnableClickEvents = true; 
PC->bEnableMouseOverEvents = true;
}


I assume I should place this code in the .cpp file only. But I get the error:

D:\Unreal Projects\Test48\Source\Test48\Test48Character.cpp(50): error C2440: ‘initializing’ : cannot convert from ‘AController *’ to ‘APlayerController *’
1> Cast from base to derived requires dynamic_cast or static_cast

So I see the types aren’t the same. Should I use the casting to get the correct type?

Yes, my mistake, sorry. You either need to cast it to APlayerController or you can just use AController. So you need to either change your code to this:



APlayerController* PC = Cast<APlayerController>(GetController());

if (PC)
{
PC->bShowMouseCursor = true; 
PC->bEnableClickEvents = true; 
PC->bEnableMouseOverEvents = true;
}


Or this:



AController* PC = GetController();

if (PC)
{
PC->bShowMouseCursor = true; 
PC->bEnableClickEvents = true; 
PC->bEnableMouseOverEvents = true;
}


Thank you, the first one is working for me - at least no problems with starting the Unreal Editor. The second doesn’t because there are no such members in AController*. The mouse cursor still disappeared at runtime, but OK I will play tomorrow.

Yes, casting… Unreal C++ is specific and I’m downloading Tom Looman’s Epic Survival Game Series to learn it. Epic Team should do something to make C++ more friendly for users, at least more updated C++ videos for beginners. It’s essential for Unity users like me.