Download

Returning ref to USTRUCT from Array

Hello,

I’m attempting to return a reference from an element in a TArray (an Array of USTRUCT). The intent is to then use that returned reference to modify the array value.



TArray<FCharacterAttribute> Attributes;

bool UAttributeComponent::GetCharacterAttribute(FGameplayTag tag, FCharacterAttribute& attribute)
{
  for (auto& value : Attributes)
  {
    if (value.ParameterTag == tag)
    {
      attribute = value;
      return true;
    }
   }
  return false;
}

I assume this is the way to do it - but it seems to come back as a value (ie modifications dont persist in the array). Any ideas how to do this?

At the moment you’re just copying the value of the array out into some other variable. You probably want to simply return a pointer instead. The easiest was to do this would be to use Attributes.FindByKey(), and provide an operator overload for the Gameplay Tag.



struct FMyTpye
{
bool operator==(const FGameplayTag& Tag) const { return ParameterTag == Tag; }
}

FMyType* Parameter = MyArray.FindByKey(Tag);
if (Parameter)
{
    // do stuff.
}


Thanks so much for the clarity!