Set/Get UProperty inside of USTRUCT directly

Structs are a little different than UObjects, but you can get and set their members like so:

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;
}
1 Like