Returning a variable from a different class crashes the engine.

Hello, whenever I run this and execute the function, the engine crashes.

   void APawnTank::Power() 
   {	
    ATankGameModeBase * useThis;

    useThis = Cast<ATankGameModeBase>(GetController());

    variableNumber = useThis ->getValue();

    if(variableNumber > 5)
    MoveSpeed = 1000.0f;
   }

This is inside another CPP file:

 int ATankGameModeBase::getValue() 
 {
  ScoreBud = 5;
  return ScoreBud;
 }

Also, the error code : Unhandled Exception: EXCEPTION_ACCESS_VIOLATION writing address 0x00000398

Does anybody know why this happens?

You, dear sir, are a life saver! Much obliged :slight_smile:

You try to cast an object of class AController (GetController()) to a Game mode class.

this will probably return a nullptr, then you try to acces the object while it doesn’t exist.

try making it something like this:

void APawnTank::Power() 
{    
	AGameModeBase* gameMode = UGameplayStatics::GetGameMode(GetWorld() );

	if(!gameMode)
	{
		// gamemode is null
		return;
	}

	ATankGameModeBase * useThis =  Cast<ATankGameModeBase>(gameMode);

	if(!useThis)
	{
		// useThis is null
		return;
	}
 
     variableNumber = useThis ->getValue();
 
     if(variableNumber > 5)
     MoveSpeed = 1000.0f;
}