Download

How to get/set struct members by name?

I have tried using this code from the ue4 answer hub:

float GetSetVectorX(UObject * ObjectWithVector)
 {
     FName PropName = FName("MyVector");
     FName VectorMemberName = FName("X");
     float NewValue = 42.0;
     
     // Get property representing struct
     UProperty * Prop = ObjectWithVector->GetClass()->FindPropertyByName(PropName);
     
     // Ensure ObjectWithVector actually has a myVector member
     if (Prop)
     {
         // Get struct address
         void * StructAddress = Prop->ContainerPtrToValuePtr<void>(ObjectWithVector);
         
         // Ensure MyVector really is a vector
         if (UStructProperty * StructProp = Cast<UStructProperty>(Prop))
         {
             // We'll get struct properties through a UScriptStruct, not a UObject
             // ScriptStructs are just templates and don't hold any of your data
             UScriptStruct * ScriptStruct = StructProp->Struct;
             
             // Get the vector's "X" property
             UProperty * ChildProp = ScriptStruct->FindPropertyByName(VectorMemberName);
 
             // Cast to FloatProperty
             if (UFloatProperty * ChildFloatProp = Cast<UFloatProperty>(ChildProp))
             {
                 // Get
                 float OldValue = ChildFloatProp->GetFloatingPointPropertyValue(StructAddress);
                 
                 // Set
                 ChildFloatProp->SetFloatingPointPropertyValue(StructAddress, NewValue);
                 
                 return OldValue;
             }
         }
     }
     return 0;
 }

It works for retrieving the X member of the stuct, but if i try to get Y, or Z member, it will just continue to return the x member.

I think the problem is, StructAddress only points to the first member. I dont know how to get the right structAddress for the other members.

Figured it out in think.
You have create another value address from ChildProp;

memberPropertyAddress = ChildProp->ContainerPtrToValuePtr(propertyAddress);