Search code examples
c++unreal-engine4

Unreal 4 illegal reference to non-static member


I'm trying to access a variable from a separate class, and I am getting an error.

    if (bSprinting){

        UPlayerPawnMovementComponent::movementSpeedMultiplier = 500.0f;
}

where the error comes from the movementSpeedMultiplier which when I hover over says: a non static reference must be relative to a specific object.

the variable in question is this one here:

public:
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override;

float movementSpeedMultiplier = 150.0f;

I know this doesn't work, I'm just totally stumped at how to make the variable editable in both classes.

Thanks in advance


Solution

  • Learn about static members.
    A skimmed down version of your problem might look like this:

    struct A{
       float movementSpeedMultiplier;
    };
    
    int main(){
      //error: invalid use of non-static data member ‘A::movementSpeedMultiplier’
      A::movementSpeedMultiplier = 500.0f;
    } 
    

    Setting the data member to static, will allow you to access the member without an instantiation.

    struct A{
       static float movementSpeedMultiplier;
    };
    float A::movementSpeedMultiplier;
    
    int main(){
    
      //compiles
      A::movementSpeedMultiplier = 500.0f;
    }