Modifying the value of an FString in an array with reflection.

I’m using reflection to get a uproperty which is an array of strings using:

bool UFunctionLibrary::SetStringArrayElementByName(UObject * Target, FName VarName, int32 index, FString NewValue)
{

	if (Target)
	{
		TArray<FString> FoundArray;
		UArrayProperty* StringArray = FindField<UArrayProperty>(Target->GetClass(), VarName);  
		TArray<FString> outArray = *StringArray->ContainerPtrToValuePtr<TArray<FString>>(Target);
		outArray[index] = NewValue;

This doesn’t appear to modify the original array, however. What I’m trying to figure out, is how to change the value at index to the value of the string NewValue

I’ve seen lots of posts about using ContainerPtrToValuePtr, and I’ve been able to return a modified array as a & parameter, but I can’t figure out how to modify the original array property. I’m trying to create a generic string array editor.

I was greatly helped by this:

And ultimately, I’m trying to create a new SetStringArrayElementByName UFUNCTION to take an index, target, a uproperty name, and a string value, and make the change.

You should try without dereferencing the pointer to the array into a variable ( it make a copy of it )

 TArray<FString>* outArray = StringArray->ContainerPtrToValuePtr<TArray<FString>>(Target);
(*outArray)[index] = NewValue;

not 100% sure, but that’s how i would do it !

1 Like

Brilliant! That worked like a charm. Thank you! For anyone up against this in the future, this is the whole code:

bool UFunctionLibrary::SetStringArrayElementByName(UObject * Target, FName VarName, int32 index, FString NewValue)
{

	if (Target)
	{
		TArray<FString> FoundArray;
		UArrayProperty* StringArray = FindField<UArrayProperty>(Target->GetClass(), VarName);  
		TArray<FString>* outArray = StringArray->ContainerPtrToValuePtr<TArray<FString>>(Target);
		(*outArray)[index] = NewValue;
		return true;
	}

	return false;
}
3 Likes