Why do I need -- if (Controller != nullptr ---?

void AShooterCharacter::MoveForward(float Value)
{
	if (Controller != nullptr && Value != 0.f)
	{
		const FRotator YawRotation(0.f, Controller->GetControlRotation().Yaw, 0.f);
		const FVector Direction(FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X));
		AddMovementInput(Direction, Value);
	}

What is practically going on when a player wants to start playing the game when the game is checking if the controller is not equal to nullptr? Why can’t we just set the movement functions for the character without checking this first?

Controller can be a nullptr when the character isn’t controlled eg client/server.

2 Likes

So I’m checking if it’s controllable?

Basically - there may also be other times it is null for code error reasons etc. It’s always good practice to check if pointers are null, it’s not slow…

1 Like

If it is equal to nullptr as you say for client/server or code error problems then it cannot be controlled . :sweat_smile:

1 Like

In the perfect world you should always check if pointer != nullptr before calling any function of that pointer.

In this case, e.g.: Axis value runs on tick, it means that it starts executing as soon as game starts. Controller value must be assigned too, I suspect it happens around BeginPlay(). So it’s quite possible that the first tick of the axis input can happen before Controller value is assigned, and without this check your game will crash, but with it the axis tick is ignored and it starts working as soon as Controller is valid.

2 Likes

@Tuerer Does this check mean the following:

Controller != nullptr > check if controller exist? and where/how is this actually checked?

Value != 0.f > check if any controller key is pressed? (since it makes no sense to move the character otherwise)