Download

How to Access Variables from another class (MyPlayerController)

I am trying to access an array variable from “MyPlayerController” in “MyEnemy” class…




// this code is in MyEnemy.cpp
	
 AMyPlayerController* ClassDefaultObject = UObject::GetClass()->GetDefaultObject<AMyPlayerController>();
	
if (ClassDefaultObject != NULL)
{

		
     GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, "BV_Array = " + FString::FromInt(ClassDefaultObject->BV_Array.Num()) );

		
}



I am guessing I am not doing this correct because when I run it… BV_Array.Num() = -172882

And when I check the BV_Array.Num() variable from inside MyPlayerController class it shows the correct amount of “4”

I looked at some example code on how to do this… but it wouldn’t compile so I needed change it to “UObject::GetClass()” and I am guessing that is causing issues, maybe?

Here is a way to access to your default “PlayerController” instance


	APlayerControllerClass* MyPlayerController = Cast<APlayerControllerClass>(GetWorld()->GetFirstPlayerController());

	if (MyPlayerController != NULL)
	{
		//...........
	}


Thanks for answering…

I had to change “APlayerControllerClass” to “APlayerController” in order to get it to compile… Was that not correct? LOL!

I am guessing it wasn’t because I have specific variables (BV_Array) in “MyPlayerController.cpp” class that doesn’t seem to show up when do it this way…

For example… “MyPlayerController.BV_Array” OR “MyPlayerController->BV_Array” Both dont exist with this instance of “MyPlayerController”

I get this error: error C2039: ‘BV_Array’ : is not a member of ‘APlayerController’
I need access to “BV_Array” variable defined in MyPlayerController.h

APlayerControllerClass is just an example , use your class instead

This works as well for grabbing the player controller without having to cast to the player controller. The only problem you might run into is a situation where you you don’t want the 0 index and would need to provide the index of the controller you wish to get.


UGameplayStatics::GetPlayerController(this, 0);