UE4 反射 学习笔记
想让类具有反射机制,必须要有这四个要素:
1、generated.h文件
2、UCLASS()宏
3、继承自UObject
4、GENERATED_BODY()
void ABlurCharacter::BeginPlay()
{
Super::BeginPlay();
ABlurCharacter *BlurCharacter = NewObject<ABlurCharacter>();
UClass *BlurCharacterClass = BlurCharacter->GetClass();
FName BlurCharacterName = BlurCharacterClass->GetFName();
GEngine->AddOnScreenDebugMessage(-1, 10.f ,FColor::Red, *BlurCharacterName.ToString());
}
这样就将类名给输出出来了
for(UProperty *Per = BlurCharacterClass->PropertyLink; Per; Per = Per->PropertyLinkNext)
{
if(Per->GetCPPType() == TEXT("FString"))
{
UStrProperty *Str = Cast<UStrProperty>(Per);
void *Addr = Str->ContainerPtrToValuePtr<void>(BlurCharacter); //从容器信息转变成具体值
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Yellow, Per->GetName() + TEXT(" ------ ") + Per->GetCPPType() +
TEXT(" ------ ") + Str->GetPropertyValue(Addr));
Str->SetPropertyValue(Addr, "AfterModified");
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Yellow, Per->GetName() + TEXT(" ------ ") + Per->GetCPPType() +
TEXT(" ------ ") + Str->GetPropertyValue(Addr));
}
}
UPROPERTY()
FString Hello = "Hello World";
获取类中FString类型的值、类型、和名称,根据代码可以看出,存储变量的数据结构是一个链表,注意,变量一定要用UPROPERTY()给包裹,不然不会将变量信息反射到链表,更不可能存取这些信息
for(TFieldIterator<UFunction> Iter(BlurCharacterClass); Iter; ++Iter)
{
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Blue, Iter->GetName());
for(TFieldIterator<UProperty> Iter1(*Iter); Iter1; ++Iter1)
{
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Black, Iter1->GetName() + TEXT(" ------ ") + Iter1->GetCPPType());
}
}
同理,自己写的函数也必须加入UFUNCTION()
void ABeginInvokeGameModeBase::BeginPlay() {
Super::BeginPlay();
AAFloorSwitch* FloorSwitch = NewObject<AAFloorSwitch>();
UClass* Father = FloorSwitch->GetClass()->GetSuperClass();
FString Name = Father->GetName();
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, Name);
}
UCLASS()
class MYCTEST_API AAFloorSwitch : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AAFloorSwitch();
}
在GameMode进行获取父类,在Actor内获取被隐藏
判断一个类是否是另一个类的父类
查找一个类的所有子类,第三个参数是找是否找子类的类,是否递归去找