Usage

Plugin在构造函数中加载的问题

在GameMode构造函数中加载(LoadObject或者ConstructorHelpers::FObjectFinder)蓝图,该蓝图使用了plugin(这里我使用了一个叫Swipe的插件),如果在构造函数中加载,则会报错:

/Game/Demo/Female/Blueprints/FemaleCharBP : Can't find file for asset. /Script/Swipe
Failed to load /Script/Swipe.SwipeComponent Referenced by K2Node_ComponentBoundEvent_2
Failed to load /Script/Swipe.SwipeComponent Referenced by K2Node_ComponentBoundEvent_3
Failed to load /Script/Swipe.SwipeComponent Referenced by SCS_Node_1

另外一种解决办法:给C++的GameMode套一个蓝图,然后在该蓝图中设置DefaultPawnClass、PlayerControllerClass等GameMode属性,此时即使这些PawnClass或者PlayerControllerClass蓝图使用了plugin,也不会报错。

添加第三方Plugin(2018-08-10更新)

工程.uproject 需要添加两处地方:
1,在 Modules 中添加 plugin 名字字符串;
2,在 Plugins 添加 plugin 信息:包括 Name 和 Enabled;

{
  "FileVersion": 3,
  "EngineAssociation": "4.20",
  "Category": "",
  "Description": "",
  "Modules": [
    {
      "Name": "MyProj",
      "Type": "Runtime",
      "LoadingPhase": "Default",
      "AdditionalDependencies": [
        "UMG",
        "Engine",
        "CoreUObject",
        "AIModule",
        "ApexDestruction",
        "MyPlugin"
      ]
    }
  ],
  "Plugins": [
    {
      "Name": "ApexDestruction",
      "Enabled": true
    },
    {
      "Name": "MyPlugin",
      "Enabled": true
    }
  ]
}
往 Plugin 中添加 C++ 代码(2018-08-13更新)

貌似没有好的办法,只能手动添加 C++ 类文件

论坛上说的这种方式不可行(至少4.20版本试过不可行):

  1. Close Visual Studio
  2. Go to your plugin classes folder
  3. Add 2 empty files TestActor.h and TestActor.cpp
  4. Then , “Generate Visual Studio Project
  5. Open Visual Studio , then the files created

Adding an Actor class to plugin?
https://forums.unrealengine.com/development-discussion/c-gameplay-programming/50761-adding-an-actor-class-to-plugin

Third Party in Plugin

Settings -> Plugins -> New Plugin -> Third Party Library

Build.cs Path:
TestTD\Plugins\Plugin2\Source\ThirdParty\Plugin2Library\Plugin2Library.Build.cs

using System.IO;
using UnrealBuildTool;

public class Plugin2Library : ModuleRules
{
    public Plugin2Library(ReadOnlyTargetRules Target) : base(Target)
    {
        Type = ModuleType.External;

        if (Target.Platform == UnrealTargetPlatform.Win64)
        {
            // Add the import library
            PublicAdditionalLibraries.Add(Path.Combine(ModuleDirectory, "x64", "Release", "ExampleLibrary.lib"));

            // Delay-load the DLL, so we can load it from the right place first
            PublicDelayLoadDLLs.Add("ExampleLibrary.dll");

            // Ensure that the DLL is staged along with the executable
            RuntimeDependencies.Add("$(PluginDir)/Binaries/ThirdParty/Plugin2Library/Win64/ExampleLibrary.dll");
        }
        else if (Target.Platform == UnrealTargetPlatform.Mac)
        {
            PublicDelayLoadDLLs.Add(Path.Combine(ModuleDirectory, "Mac", "Release", "libExampleLibrary.dylib"));
            RuntimeDependencies.Add("$(PluginDir)/Source/ThirdParty/Plugin2Library/Mac/Release/libExampleLibrary.dylib");
        }
    }
}

Building

Plugin Package Command

This command equals the operation of Package button under Plugins panel:

F:\Epic Games\UE_4.24\Engine\Binaries\DotNET\UnrealBuildTool.exe UE4Editor Win64 Development -Project=E:\Build\P2\HostProject\HostProject.uproject -plugin=E:\Build\P2\HostProject\Plugins\P2\P2.uplugin -iwyu -noubtmakefiles -manifest=E:\Build\P2\HostProject\Saved\Manifest-UE4Editor-Win64-Development.xml -nohotreload -log="C:\Users\Neil\AppData\Roaming\Unreal Engine\AutomationTool\Logs\F+Epic+Games+UE_4.24\UBT-UE4Editor-Win64-Development.txt"
Plugin Building Command

The first step is to build the plugin for distribution in the normal manner. This can be done using the UnrealBuildTool with the following command:

UE4Dir\Engine\Build\BatchFiles\RunUAT.bat BuildPlugin -Rocket -Plugin=Plugin.uplugin -TargetPlatforms=Win64 -Package=OutputDir

Reference:
https://mercuna.com/building-binary-plugins-in-unreal-engine-4/

Build Project whitout plugin source (Pre-build)

Issue 1: ERROR: Missing precompiled manifest for ‘TestPlugin’

If you plan to build project with plugin source removed (use binaries only), you should package your plugin at first:
Settings -> Plugins -> Find you plugins and click Package under plugin tab, then replace original plugin with new plugin which was packaged before.
Otherwise the binaries of plugins builded under VisualStudio aren unusable for building project.

If you didn’t Package build using the way above, there’s a error at building project:

UATHelper: Packaging (Windows (64-bit)):   ERROR: Missing precompiled manifest for 'TestPlugin'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in TestPlugin.build.cs to override.
PackagingResults: Error: Missing precompiled manifest for 'TestPlugin'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in TestPlugin.build.cs to override.

Issue 2: ERROR: Could not find definition for module

Error at buling project:

UATHelper: Packaging (Windows (64-bit)):   ERROR: Could not find definition for module 'MyPlugin' (referenced via default plugins -> MyPlugin.uplugin)
PackagingResults: Error: Could not find definition for module 'MyPlugin' (referenced via default plugins -> MyPlugin.uplugin)

Caused by:
Missed source code of plugin.

Only Editor workd if there’s no source code in game project plugins, and project building would fail.

Solution:
If you want to get your plugin working at building project, also keep plugin source in private, you need to deliver engine binaries from source building:
Put your plugin source in `UE4Dir\Engine\Plugins\` and build engine from source, then remove source code of plugin.

Issue 3: Fatal error C1083: Cannot open include file: ‘MyActor.generated.h’

Error at builing project:

fatal error C1083: Cannot open include file: 'MyActor.generated.h'

Caused by:
If set bUsePrecompiled = true; in Build.cs of plugin, maybe you clean Intermediate directory, so it build failed at first building.

Solution:
Set bUsePrecompiled = false; at first, then build project, then set bUsePrecompiled = true;

Issues

Warning: Modules must specify an explicit precompiled header

Warning at building project:

MyPlugin.Build.cs: warning: Modules must specify an explicit precompiled header (eg. PrivatePCHHeaderFile = "Private/MyProjPrivatePCH.h") from UE 4.21 onwards.

Reason:
plugin’s configuration had changed from 4.21 onwards.

Solution:

Replace MyProj\Plugins\MyPlugin\Source\MyPlugin\MyPlugin.Build.cs with following contents:

using UnrealBuildTool;

public class MyPlugin : ModuleRules
{
    public MyPlugin(ReadOnlyTargetRules Target) : base(Target)
    {
        PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
		
        PublicIncludePaths.AddRange(
            new string[] {
                // ... add public include paths required here ...
            }
            );
				
		
        PrivateIncludePaths.AddRange(
            new string[] {
                "MyPlugin/Private",
                // ... add other private include paths required here ...
            }
            );
			
		
        PublicDependencyModuleNames.AddRange(
            new string[]
            {
                "Core",
                // ... add other public dependencies that you statically link with here ...
            }
            );
			
		
        PrivateDependencyModuleNames.AddRange(
            new string[]
            {
                "CoreUObject",
                "Engine",
                "Slate",
                "SlateCore",
                // ... add private dependencies that you statically link with here ...	
            }
            );
		
		
        DynamicallyLoadedModuleNames.AddRange(
            new string[]
            {
                // ... add any modules that your module loads dynamically here ...
            }
            );
    }
}
Error: Expected MyPlugin.h to be first header included.

Error at building project:

MyPlugin.cpp(1): error: Expected MyPlugin.h to be first header included.

Reason:
The rules of cpp sources in plugin had changed from 4.21 onwards.

Solution:
Using the following template sources in plugin, replace string MyPlugin with YourPlugin.

MyProj\Plugins\MyPlugin\Source\MyPlugin\Public\MyPlugin.h

#pragma once

#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"

DECLARE_LOG_CATEGORY_EXTERN(MyPlugin,Log,All);

class FMyPluginModule : public IModuleInterface
{
public:

    /** IModuleInterface implementation */
    virtual void StartupModule() override;
    virtual void ShutdownModule() override;
};

MyProj\Plugins\MyPlugin\Source\MyPlugin\Private\MyPlugin.cpp

#include "MyPlugin.h"

#define LOCTEXT_NAMESPACE "FMyPluginModule"
DEFINE_LOG_CATEGORY(MyPlugin);
void FMyPluginModule::StartupModule()
{
    // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
}

void FMyPluginModule::ShutdownModule()
{
    // This function may be called during shutdown to clean up your module.  For modules that support dynamic reloading,
    // we call this function before unloading the module.
}

#undef LOCTEXT_NAMESPACE
	
IMPLEMENT_MODULE(FMyPluginModule, MyPlugin)
Fatal error C1852: SharedPCH.Engine.h.pch is not a valid precompiled header file

Error at building project:

MyProj\Plugins\MyPlugin\Intermediate\Build\Win64\UE4Editor\Development\MyPlugin\Module.MyPlugin.gen.cpp: fatal error C1852: 'D:\MyProj\Intermediate\Build\Win64\MyProjEditor\Development\Engine\SharedPCH.Engine.h.pch' is not a valid precompiled header file

Reason:
Maybe caused by cache files of building.

Solution:
Remove directory [Project]/Intermediate and [Project]/Saved, then regenerate project files.

error LNK2019: unresolved external symbol “__declspec(dllimport) public: static bool __cdecl FRHIResource::Bypass(void)”

Error at building project:

Module.OpenCV.cpp.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static bool __cdecl FRHIResource::Bypass(void)" (__imp_?Bypass@FRHIResource@@SA_NXZ) referenced in function "public: __cdecl TRefCountPtr<class FRHITexture2D>::~TRefCountPtr<class FRHITexture2D>(void)" (??1?$TRefCountPtr@VFRHITexture2D@@@@QEAA@XZ)
Module.OpenCV.cpp.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static enum ENamedThreads::Type __cdecl FRenderCommand::GetDesiredThread(void)" (__imp_?GetDesiredThread@FRenderCommand@@SA?AW4Type@ENamedThreads@@XZ) referenced in function "private: class TRefCountPtr<class FGraphEvent> __cdecl TGraphTask<class `protected: void __cdecl AWebcamReader::UpdateTextureRegions(class UTexture2D *,int,unsigned int,struct FUpdateTextureRegion2D *,unsigned int,unsigned int,unsigned char *,bool)'::`5'::EURCMacro_UpdateTextureRegionsData>::Setup(class TArray<class TRefCountPtr<class FGraphEvent>,class TInlineAllocator<4,class FDefaultAllocator> > const *,enum ENamedThreads::Type)" (?Setup@?$TGraphTask@VEURCMacro_UpdateTextureRegionsData@?4??UpdateTextureRegions@AWebcamReader@@IEAAXPEAVUTexture2D@@HIPEAUFUpdateTextureRegion2D@@IIPEAE_N@Z@@@AEAA?AV?$TRefCountPtr@VFGraphEvent@@@@PEBV?$TArray@V?$TRefCountPtr@VFGraphEvent@@@@V?$TInlineAllocator@$03VFDefaultAllocator@@@@@@W4Type@ENamedThreads@@@Z)
Module.OpenCV.cpp.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static enum ESubsequentsMode::Type __cdecl FRenderCommand::GetSubsequentsMode(void)" (__imp_?GetSubsequentsMode@FRenderCommand@@SA?AW4Type@ESubsequentsMode@@XZ) referenced in function "public: static class TGraphTask<class `protected: void __cdecl AWebcamReader::UpdateTextureRegions(class UTexture2D *,int,unsigned int,struct FUpdateTextureRegion2D *,unsigned int,unsigned int,unsigned char *,bool)'::`5'::EURCMacro_UpdateTextureRegionsData>::FConstructor __cdecl TGraphTask<class `protected: void __cdecl AWebcamReader::UpdateTextureRegions(class UTexture2D *,int,unsigned int,struct FUpdateTextureRegion2D *,unsigned int,unsigned int,unsigned char *,bool)'::`5'::EURCMacro_UpdateTextureRegionsData>::CreateTask(class TArray<class TRefCountPtr<class FGraphEvent>,class TInlineAllocator<4,class FDefaultAllocator> > const *,enum ENamedThreads::Type)" (?CreateTask@?$TGraphTask@VEURCMacro_UpdateTextureRegionsData@?4??UpdateTextureRegions@AWebcamReader@@IEAAXPEAVUTexture2D@@HIPEAUFUpdateTextureRegion2D@@IIPEAE_N@Z@@@SA?AVFConstructor@1@PEBV?$TArray@V?$TRefCountPtr@VFGraphEvent@@@@V?$TInlineAllocator@$03VFDefaultAllocator@@@@@@W4Type@ENamedThreads@@@Z)
Module.OpenCV.cpp.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) class FRHICommandListImmediate & __cdecl GetImmediateCommandList_ForRenderCommand(void)" (__imp_?GetImmediateCommandList_ForRenderCommand@@YAAEAVFRHICommandListImmediate@@XZ) referenced in function "public: void __cdecl `protected: void __cdecl AWebcamReader::UpdateTextureRegions(class UTexture2D *,int,unsigned int,struct FUpdateTextureRegion2D *,unsigned int,unsigned int,unsigned char *,bool)'::`5'::EURCMacro_UpdateTextureRegionsData::DoTask(enum ENamedThreads::Type,class TRefCountPtr<class FGraphEvent> const &)" (?DoTask@EURCMacro_UpdateTextureRegionsData@?4??UpdateTextureRegions@AWebcamReader@@IEAAXPEAVUTexture2D@@HIPEAUFUpdateTextureRegion2D@@IIPEAE_N@Z@QEAAXW4Type@ENamedThreads@@AEBV?$TRefCountPtr@VFGraphEvent@@@@@Z)
Module.OpenCV.cpp.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) bool GRHINeedsExtraDeletionLatency" (__imp_?GRHINeedsExtraDeletionLatency@@3_NA)
Module.OpenCV.cpp.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) private: static class TLockFreePointerListUnordered<class FRHIResource,64> FRHIResource::PendingDeletes" (__imp_?PendingDeletes@FRHIResource@@0V?$TLockFreePointerListUnordered@VFRHIResource@@$0EA@@@A)
Module.OpenCV.cpp.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) class FDynamicRHI * GDynamicRHI" (__imp_?GDynamicRHI@@3PEAVFDynamicRHI@@EA)
Module.OpenCV.cpp.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) class FRHICommandListExecutor GRHICommandList" (__imp_?GRHICommandList@@3VFRHICommandListExecutor@@A)
Module.OpenCV.cpp.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) bool GIsThreadedRendering" (__imp_?GIsThreadedRendering@@3_NA)
Module.OpenCV.cpp.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) class TAtomic<bool> GMainThreadBlockedOnRenderThread" (__imp_?GMainThreadBlockedOnRenderThread@@3V?$TAtomic@_N@@A)

Reason:
Miss required PublicDependencyModuleNames: RHI and RenderCore.

Solution:
Add module names in MyPlugin.Build.cs

PublicDependencyModuleNames.AddRange(
    new string[]
    {
        "Core",
        "RHI",
        "RenderCore",
    }
    );

Origin:
https://usagi.hatenablog.jp/entry/2018/09/11/205922

ERROR: Remote compiling requires a server name

Error at packaging plugin:

ERROR: Remote compiling requires a server name. Use the editor (Project Settings > IOS) to set up your remote compilation settings.

Caused by:
By default, plugin building includes all platforms even current device don’t support.

Solution:
Specify platform name that current device support.

Example in *.uplugin:

{
    "FileVersion" : 3,
    "Version" : 1,
    "VersionName" : "1.0",
    "FriendlyName" : "Victory Plugin",
    "Description" : "120+ Custom Blueprint Nodes For You! <3 Rama",
    "Category" : "Rama",
    "CreatedBy" : "Rama",
    "CreatedByURL" : "http://www.ue4code.com",
    "DocsURL" : "http://www.ue4code.com",
    "MarketplaceURL" : "http://www.ue4code.com",
    "SupportURL" : "http://www.ue4code.com",
    "EnabledByDefault" : true,
    "CanContainContent" : false,
    "IsBetaVersion" : false,
    "Installed" : true,
    "RequiresBuildPlatform" : false,
    "Modules" :
    [
        {
            "Name" : "VictoryBPLibrary",
            "Type" : "Runtime",
            "LoadingPhase" : "PreDefault",
            "WhitelistPlatforms" :
            [
                "Win64",
                "Win32",
                "HTML5"
            ]
        }
    ]
}

Reference:
https://wiki.unrealengine.com/How_To_Package_Plugins_For_UE4_Marketplace#.Uplugin_White_List

error C4273: ‘VA::Json::Features::Features’: inconsistent dll linkage

Error at building plugin:

error C4273: 'VA::Json::Features::Features': inconsistent dll linkage.

Caused by:
Your source in plugin contains JSON_API that was not adapted whit your plugin macro(e.g. MYPLUGIN_API).

Solution:
Rename all JSON_API to your plugin macro(e.g. MYPLUGIN_API).

Reference

How to Install a Plugin on Unreal Engine 4
https://idkudk.blogspot.jp/2015/02/how-to-install-plugin-on-unreal-engine-4.html

UE4/Plugin installation
https://wiki.popcornfx.com/index.php/UE4/Plugin_installation

Origin: Building Binary Plugins In Unreal Engine 4
https://mercuna.com/building-binary-plugins-in-unreal-engine-4/

Plugins
https://docs.unrealengine.com/en-US/Programming/Plugins/index.html

How To Package Plugins For UE4 Marketplace
https://wiki.unrealengine.com/How_To_Package_Plugins_For_UE4_Marketplace


醉里挑灯看剑,梦回吹角连营。----辛弃疾《破阵子·为陈同甫赋壮词以寄之》