【UE C++】通过FString获取到UEnum值的方法

【UE C++】通过FString获取到UEnum值的方法

前言

在数字孪生项目中涉及到Web端调用后端方法的交互,一般情况下是前端通过某些交互(如PixelStreaming emitUIInteraction)发送一个序列化的Json到UE ,UE进行解析后分发到各功能模块执行相应的方法。
如果我们把某些关键的Controller或者方法大类定义成枚举,不但要在前后端各维护一份枚举对应,而且在前端传来的Value中只能拿到uint8类型的数据。在查看调用日志时看见 Method: 2 属实大脑要宕机一下。

但其实依赖UE UEnum强大的反射机制,有一些办法可以通过FString获取到UEnum值

UEnum源码

实用Api

通过名字获取索引

int32 GetIndexByName(FName InName, EGetByNameFlags Flags = EGetByNameFlags::None) const;

通过索引获取名字
FName GetNameByIndex(int32 Index) const;

通过值获取索引下标
FORCEINLINE int32 GetIndexByValue(int64 InValue) const

通过下标获取值
FORCEINLINE int64 GetValueByIndex(int32 Index) const

通过下标获取显示名称
virtual FText GetDisplayNameTextByIndex(int32 InIndex) const;

获取索引最大值
int64 GetMaxEnumValue() const;

检查索引是否有效,加强代码稳定性

/** Checks if enum has entry with given value. Includes autogenerated _MAX entry. */
bool IsValidEnumValue(int64 InValue) const;

/** Checks if enum has entry with given name. Includes autogenerated _MAX entry. */
bool IsValidEnumName(FName InName) const;

通过枚举值名称获取值

int64 UEnum::GetValueByNameString(const FString& SearchString, EGetByNameFlags Flags) const
{
	int32 Index = GetIndexByNameString(SearchString, Flags);

	if (Index != INDEX_NONE)
	{
		return GetValueByIndex(Index);
	}

	return INDEX_NONE;
}

通过枚举值名称获取值

int64 UEnum::GetValueByNameString(const FString& SearchString, EGetByNameFlags Flags) const
{
	int32 Index = GetIndexByNameString(SearchString, Flags);

	if (Index != INDEX_NONE)
	{
		return GetValueByIndex(Index);
	}

	return INDEX_NONE;
}

实战例子

通过FString 拿到EYourEnumName::XXX 这样的枚举值

// 一个拿到前端Json 解析执行的方法。
void UMethodManager::Excute(TSharedPtr<FJsonObject> data) {
    // 拿到从前端传来的Enum对应的名称
	FString toolName = data->GetStringField("toolName");
	// 从所有UObject中寻找类型为UEnum 名称为EYourEnumName的UEnum指针
	const UEnum* currentEnum = FindObject<UEnum>(ANY_PACKAGE, TEXT("EYourEnumName"), true);
	// 获取Name对应的UEnum的Value
	int64 currentEnumValue = currentEnum->GetValueByNameString(toolName);
	// 容错判断,判断这个值在枚举中是否合法。
	bool isEnumValid = currentEnum->IsValidEnumValue(currentEnumValue);
	// . 上面的代码判断String转到EnumValue后是否合法 
	if (isEnumValid) {
		// EYourEnumName(value)  就可以拿到对应的枚举
			ExcuteXXX(EYourEnumName(currentEnumValue));
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值