简体   繁体   中英

Access static variable in a different class in C++/Unreal Engine 4

I have a static variable declared in a header file and initialized in the corresponding cpp file. What I'm trying to do is accessing that variable from another cpp file. This is the code:

AkOcclusionObstructionService.h

class AkOcclusionObstructionService
{
public:

    static float OcclusionFadeRate;
    ...
}

AkOcclusionObstructionService.cpp

...
float AkOcclusionObstructionService::OcclusionFadeRate = 3.0f;
...

MyBlueprintFunctionLibrary.cpp

#include "MyBlueprintFunctionLibrary.h"
#include "AkOcclusionObstructionService.h"

void UMyBlueprintFunctionLibrary::ChangeWwiseFadeRate(float rate)
{
    AkOcclusionObstructionService::OcclusionFadeRate = rate;
}

When I try to build Visual Studio gives me this error:

" LNK2001 unresolved external symbol "public: static float AkOcclusionObstructionService::OcclusionFadeRate" (?OcclusionFadeRate@AkOcclusionObstructionService@@2MA) ".

It looks like MyBlueprintFunctionLibrary can't see the OcclusionFadeRate variable in the AkOcclusionObstructionService cpp file.

Anyone has an idea of what is happening?

Thanks in advance!

EDIT: Additional Linking/building info:

To make the " AkOcclusionObstructionService.h " file visible to the " MyBlueprintFunctionLibrary.cpp " file we had to add something to the " TestFadeRateWwise2.build.cs " (TestFadeRateWwise2 is the project name). Specifically we had to add "AKAUDIO" to this line:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "AKAUDIO" });

That's the only "non standard" thing we did.

in the cpp file you should do like this.

//.cpp
#include "MyBlueprintFunctionLibrary.h"
#include "AkOcclusionObstructionService.h"

//this line make this file to access the static parameter.
float AkOcclusionObstructionService::OcclusionFadeRate;

void UMyBlueprintFunctionLibrary::ChangeWwiseFadeRate(float rate)
{
    OcclusionFadeRate = rate;
}

It is hard to tell based on the code you posted but I assume the issue is because the line below is within a function:

float AkOcclusionObstructionService::OcclusionFadeRate = 3.0f;

Move that line outside the function and try it again. You can take a look at this question: How to access static members of a class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM