1.新建UE4项目(with cpp)
//非cpp项目,直接新建cpp文件也可以
//编译后重新打开UEEditor可以看到
2.新建第二个Module
1)文件目录如下:
2)代码如下:
OtherModule.Build.cs
using UnrealBuildTool;
public class OtherModule : ModuleRules
{
public OtherModule(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
}
}
OtherModule.h
#pragma once
#include "Engine.h"
#include "ModuleInterface.h"
class IOtherModuleInterface : public IModuleInterface
{
public:
virtual int Add(int num1,int num2) =0;
virtual void doNothing() =0;
};
OtherModule.cpp
#include "OtherModule.h"
class OtherModuleImpl :public IOtherModuleInterface
{
public:
virtual void StartupModule() override
{
}
virtual int Add(int num1, int num2) override
{
return num1 + num2;
}
virtual void doNothing() override
{
}
};
IMPLEMENT_GAME_MODULE(OtherModuleImpl, OtherModule);
3.在MainModule中使用
1)在MainModule.Build.cs中增加依赖
public MainModule(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay" });
PrivateDependencyModuleNames.AddRange(new string[] { "OtherModule"});
}
2)在其他的任意类中使用(此处使用一个actor)
#include "OtherModule.h"
// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
Super::BeginPlay();
if (GEngine)
{
IOtherModuleInterface* OtherModule = FModuleManager::LoadModulePtr<IOtherModuleInterface>("OtherModule");
if (OtherModule != nullptr)
{
OtherModule->doNothing();
GEngine->AddOnScreenDebugMessage(-1, 20, FColor::Yellow, FString::FromInt(OtherModule->Add(1, 2) + 2));
}
GEngine->AddOnScreenDebugMessage(-1, 20, FColor::Yellow, FString("hello_AMyActor222"));
}
}
4.在vs中右键Build,在UE4中compile并run
其他:
1)GEngine报错,请将MainModule.h中的include文件改为“Engine.h”;
2)如果vs编译和ue4compile没有错误,但是没有打印结果(LoadModulePtr为空),请将UEEditor关闭重开,弹出对话框是否重新编译OtherModule.lib,选是,这时候就能打印结果了。
3)virtual void doNothing() =0;表示该函数为声明函数,只有子类实现,去掉OtherModule.cpp无法编译
4)OtherModule.h中的IOtherModuleInterface和OtherModuleImpl必须是分离的,不然编译不通过。
这也说明,lib中暴露的函数必须都放在IOtherModuleInterface中。
5)如果修改lib中的内容,有时候需要rebuild而不是build。
6)参考网址:
http://blog.youkuaiyun.com/jack0596_cn/article/details/52387890
https://forums.unrealengine.com/showthread.php?65944-c-Mysql-database-error&highlight=mysql
https://www.youtube.com/watch?v=piPkLJerpTg
https://docs.unrealengine.com/latest/INT/Programming/Modules/Gameplay/