How to change Max speed of a character in an Actorcomponent

I am trying to change the walking max speed of my character in a actor component.

Thats my code, but it is not working and I am not sure why:

ACharacter* myCharacter = Cast<ACharacter>(GetOwner()); 

UCharacterMovementComponent* CharacterMovement = myCharacter->GetCharacterMovement();  //this line makes my Engine crash
CharacterMovement->MaxWalkSpeed = 100.0f;

Your crash is probably being caused by a null pointer exception. In this case, it could mean your cast is failing for some reason.

As a general rule, you should always make sure that your pointers are valid before trying to de-reference and use them. This means you need to make sure they point to some memory address, and aren’t equal to nullptr.

You could wrap a simple if (myCharacter != nullptr) condition around your myCharacter->GetCharacterMovement() call to prevent the crash, but you’ll still need to decide how you want to handle what happens if your myCharacter pointer remains null after the cast.

Of course, the cast shouldn’t fail, and neither should the GetOwner() call, so there’s definitely a problem there.

So, your next steps are to figure out why your cast to ACharacter is failing, and remember to check that your pointers are valid before trying to de-reference them.

Well, the cast does not fail because it works fine when I call mycharacter->GetController(). so I am not sure what is wrong with the GetMovement() call

I just got a hunch. Try running something like this at the top of your constructor and let me know what happens:

if (GetOwner() == nullptr)
{
    UE_LOG(LogTemp, Error, TEXT(“Couldn’t get owning actor!”));
}
return;

You’ll have to check the developer log in the editor to see that log message, but I strongly suspect that it will show up and prove that, at the moment the component is constructed, it has no owner yet.

I want you to check to be sure, but I just stumbled into this problem yesterday evening in my own project. I’m now almost convinced that this is expected behavior that just isn’t very intuitive.

Let me know whether your component’s owner is also null during construction and we’ll probably both learn something.