在UE4中使用Module

本文详细介绍了如何在UE4中创建并使用自定义模块,包括新建项目、添加模块、实现接口及在主模块中调用等功能,适用于希望扩展UE4功能的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值