找回密码
 立即注册
查看: 397|回复: 0

如何编写UE4插件,简析插件系统

[复制链接]
发表于 2022-1-31 06:02 | 显示全部楼层 |阅读模式
在UE4里添加自定义插件很简单,下面以一个Editor插件为例讲解,分为以下几个步骤:

1. .uproject用的是jason格式,它定义了工程的各部分信息。在.uproject 中声明插件模块,第一个模块是Game模块,第二个是plugin模块。在Modules字段下加入如下代码:
"FileVersion": 3,
"EngineAssociation": "4.11",
"Category": "",
"Description": "",
"Modules": [
{
"Name": "UE4Cookbook",
"Type": "Runtime",
"LoadingPhase": "Default",
"AdditionalDependencies": [
"Engine",
"CoreUObject"
]
},
{
"Name": "Ranging",
"Type": "Editor",
"LoadingPhase": "Default",
"AdditionalDependencies": [
"Engine",
"CoreUObject"
]
}
]
}Ranging为示例名字,以下所有步骤中都替换为自己的插件模块名。
模块的格式主要有以下几个属性:

  • Name:模块名字
  • Type:模块类型,只在运行时加载Runtime,或者是只在编辑器下加载Editor
  • Loadingphase:决定加载顺序
  • AdditionalDependencies:所依赖的模块名字
这个步骤是可选项,可以手动写入uproject,执行Generateproject后会生效,也可以在编辑器中Plugin设置里勾选加载。

2. 在Content目录下建立Content/Plugins/YourPluginName 的目录结构,在此目录下添加YourPluginName.build.cs文件。添加以下内容:
using UnrealBuildTool;
public class Ranging : ModuleRules
{
public Ranging (TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] {
"Core", "CoreUObject", "Engine", "InputCore", "RHI",
"RenderCore", "ShaderCore" });
PublicDependencyModuleNames.Add(" ");
PrivateDependencyModuleNames.AddRange(new string[] {
"UnrealEd" });
}
}
此文件是UE4用来构建工程和依赖的C#文件,类似于makefile/cmake的作用,其中引用UnrealBuildTool(UBT),实现ModuleRules类,TargetInfo 是指编译的目标平台(win/mac/linux)。通过如PublicDependencyModuleNames等接口添加依赖模块,头文件源文件路径,lib和dll路径。
如果模块中需要引用此插件的其他模块,亦要将所依赖的模块名包含在内。

3. 在.uplugin文件下加入模块及其属性描述,如下所示,书写方法如1步骤中一致,注意,如果插件中添加多个模块,则所有模块都必须写入.uplugin文件中,依照引用关系确立载入顺序。
{
"FileVersion": 3,
"Version": 1,
"VersionName": "1.0",
"FriendlyName": "Ranging",
"Description": " ",
"Category": "Other",
"CreatedBy": "Eric",
"CreatedByURL": "",
"DocsURL": "",
"MarketplaceURL": "",
"SupportURL": "",
"CanContainContent": true,
"IsBetaVersion": false,
"Installed": false,
"Modules": [
  {
   "Name": "Ranging",
   "Type": "Editor",
   "LoadingPhase": "Default"
  }
]
}4. 在Content/Plugins/YourPluginName路径下添加Public和Private文件夹,分别添加YourPluginName.h和YourPluginName.cpp,在YourPluginName.h中加入如下代码,实现IModuleInterface接口,用于加载模块和卸载模块。
#pragma once
#include "Engine.h"
#include "ModuleManager.h"
#include "UnrealEd.h"
class FRangingModule: public IModuleInterface
{
};
在YourPluginName.cpp中加入如下代码:
#include "Ranging.h"
IMPLEMENT_GAME_MODULE(FRangingModule, Ranging)IMPLEMENT_GAME_MODULE会申明一个Exported C函数,UE4只需要调用InitializeModule()就会会返回一个此模块的实例,而不需要知道此模块的类型。

5. 用Generateproject命令生成工程,UBT和UHT就会建立所有Plugin的依赖关系和引用,用VS打开后,可以看到插件文件在工程中,编译通过后,插件添加完成。


如果要在插件中添加多个模块,如需要区分Editor下运行的和Runtime下运行的模块,亦可以按照之前方式,在Content/Plugins/下添加多个模块文件夹,如Content/Plugins/YourPluginNameEditor,Content/Plugins/YourPluginNameRuntime,一般在名字后面加类型。之后别忘了在.uplugin下申明模块。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-6 23:19 , Processed in 0.097698 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表