UE5 C++ 反射 运行时获取类和字符串的信息
一.首先我们在上篇文章的基础上,再创建一个GameMode
在里面去拿 反射的类的信息,也就时 元数据的 具体信息
二.如何
首先我们需要创建一个UStudent类,它本身拥有反射的。
接着使用UClass ,指向这个 UStudent 类。
1.使用GetClass() 获取反射类的类型,而这个方法来自于UObjectBase,经常看大钊的UObject的应该很熟悉这个。


源代码注释里说明了,它是UObject更下一层级的接口。上面几个U开头的类都要用它。

2.同理GetFName,也是UObjectBase里的方法。不过它是获取反射类的名字
3.获得UPROPERTY名字,的 FField::GetName()

而UFileld是专门管理 反射对象的

这里截取inside UE4的一些思考,(38 封私信 / 80 条消息) 《InsideUE4》UObject(三)类型系统设定和结构 - 知乎



4. 获得Property的类型, GetCPPTpe().
再升入可以发现,它是泛型的。每个类型都有自己的GetCPPType()

5.测试代码 在GameMode里测试Student,的运行时,获得它的属性,类信息
#include "ReflectionGameModeBase.h"
#include "Student.h"AReflectionGameModeBase::AReflectionGameModeBase()
{UE_LOG(LogTemp,Warning,TEXT("Helleo Reflection"));UStudent* Student = NewObject<UStudent>();UClass* StudentClass = Student->GetClass(); //获取类FName ClassName = StudentClass->GetFName(); //获取类名称UE_LOG(LogTemp,Warning,TEXT("Student's classname is %s"),*ClassName.ToString());for (FProperty* Property = StudentClass->PropertyLink; Property; Property = Property->PropertyLinkNext){FString PropertyName = Property->GetName(); //运行时获得属性名FString PropertyType = Property->GetCPPType(); //运行时获得属性类型if (PropertyType == "FString"){FStrProperty* StringProperty = CastField<FStrProperty>(Property); //转换为字符串类型void* Addr = StringProperty->ContainerPtrToValuePtr<void>(Student); //从容器到值的结构,一个类有一份但是值有多份。FString PropertyValue = StringProperty->GetPropertyValue(Addr);//StringProperty->GetPropertyValue(Addr);UE_LOG(LogTemp, Warning, TEXT("Student's Properties has %s Type is %s Value is %s"), *PropertyName, *PropertyType, *PropertyValue);}int32 a = 1;}int32 a = 1;
}
