how can I store my character reference in a variable?
every thing works fine when I’m using AController::GetCharacter();
but when I’m trying to store the character in a variable
like AMyProjectCharacter* myCharacter = Cast<AMyProjectCharacter>(AController::GetCharacter());
or AMyProjectCharacter * myCharacter = AController::GetCharacter();
I’m getting build errors
sow how can I do it?
and is it better to keep using AController::GetCharacter();
?
in terms of performance?
You should keep using this. Reason is that the character pointer is only pointing towards a character while the controller possesses one. If you store a pointer in another class you will have to keep that pointer updated manually when the controller possesses, unpossesses one which is messy.
But to answer the post title “How can I store my character reference in a variable? c++”:
ACharacter* MyCharacter = MyController->GetCharacter();
The reason your line is not working is because you are calling AController::GetCharacter which attempts to call GetCharacter without an instance of a controller. This way of calling a method is only valid if the method is static. Instead you must first get a pointer to the controller you want (AController* MyController = …) and call GetCharacter on MyController.
This is also invalid:
AMyProjectCharacter* myCharacter = Cast(AController::GetCharacter());
Because you must cast to something ( <> ):
AMyProjectCharacter* MyProjectCharacter = Cast<AMyProjectCharacter>(MyCharacter);
and what about casting to get access to myCharacter functions should I cast every time or store the character once in a variable?
You can Cast when you need it, no need to store it in a new variable. There will be no performance difference.