如何在C++中创建可被Blueprint调用的全局函数

继承蓝图函数库UBlueprintFunctionLibrary,实现保存文件到硬盘

概流程:

1+创建一个C++类,继承自UBlueprintFunctionLibrary。这里需要注意一点,在编辑器中不能添加父类为UBlueprintFunctionLibrary的c++类. 所以需要先利用编辑器一个继承自任意类的c++类,之后在头文件中更改.

2+UBlueprintFunctionLibrary子类中,带有BlueprintCallable属性的函数都可以在Blueprint中调用.

3+函数带有BlueprintPure属性,则说明此函数不会修改任何游戏状态,因此无需exec链的触发(在Blueprint中体现为没有白线输入),可以在任何时刻被调用获取其结果.

4+声明为静态函数,故此创建的蓝图函数库可以在任何工程中使用.

具体代码如下:

UxwlBlueNode.h
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "xwlBlueNode.generated.h"
/**
 * 
 */
UCLASS()
class UxwlBlueNode : public UBlueprintFunctionLibrary
{
    GENERATED_UCLASS_BODY()
    UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Test")
    static FString GetHappyMessage();
 
    UFUNCTION(BlueprintCallable, Category = "Test")
    static bool SaveToFile(FString Dir, FString Name, FString Text, bool Overwrite = false);
};
 
UxwlBlueNode.cpp
#include "xwlBlueNode.h"
UxwlBlueNode::UxwlBlueNode(const class FPostConstructInitializeProperties& PCIP)
    : Super(PCIP)
{
}
FString UxwlBlueNode::GetHappyMessage() {
    return FString("Hello, I'm Happy!");
}
 
bool UxwlBlueNode::SaveToFile(
    FString Dir,
    FString Name,
    FString Text,
    bool Overwrite
    )
 {
    IPlatformFile& F = FPlatformFileManager::Get().GetPlatformFile();
    if (!F.DirectoryExists(*Dir))
    {
        F.CreateDirectoryTree(*Dir);
        if (!F.DirectoryExists(*Dir))
        {
            return false;
        }
    }
    Dir += "\\";
    Dir += Name;
 
    if (!Overwrite)
    {
        if (F.FileExists(*Dir))
        {
            return false;
        }
    }
    return FFileHelper::SaveStringToFile(Text, *Dir);
}


其中特别注意到SaveToFile参数FString 类型,当参数传进来后,居然用到了*操作符,这是很怪异的.其实我们参看FString定义可以看出:

UnrealString.h	
/**
	 * Get pointer to the string
	 *
	 * @Return Pointer to Array of TCHAR if Num, otherwise the empty string
	 */
	FORCEINLINE const TCHAR* operator*() const
	{
		return Data.Num() ? Data.GetTypedData() : TEXT("");
	}

这是FString内部对*操作符的重载.一切尽在不言中!

最后在蓝图中使用:


参考链接:

https://wiki.unrealengine.com/Blueprint_Function_Library,_Create_Your_Own_to_Share_With_Others

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

failwest9527

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值