How to reference (and modify) a c++ array from blueprint?


I defined a private array member in a class like this:

TArray<FWeightedQuantity> Resources;

Now I want to expose the arry through a function that returns a reference to the array:

TArray<FWeightedQuantity>& GetResources();

So that I can modify the array in blueprints:


However, the array stays unmodified as if a copy was returned by the function rather than a reference.

What is the correct way to do it?
Any help is appreciated :slight_smile:


I’m not sure you can create an UFUNCTION that returns a reference. In this case, there’s really no problem in making the array blueprint-accessible since even if you could return a reference to it, callers could modify the array in the same ways as they can using a public property (they could call clear() on it, for example). If you want to restrict access to the array you should use methods like GetResourceCount(), GetResourceAt(int index) and AddResource(const FWeightedQuantity& Resource).


Yeah. Was thinking around too many corners here :slight_smile: Im just used to the practice of never having public class member fiels, only methods, even for trivial assignment accessors.

void GetResources ( UPARAM(ref) TArray<FWeightedQuantity> & OutResources )

[USER=“434”]BrUnO XaVIeR[/USER]
Thanks :slight_smile: Didnt know about the UPARAM specifier… Will look it up further.

I think the composite type in UnrealScript like Array works similar to primitive type. They would be assigned to other variable or passed in function calls create a copy of data. To reference a variable, the variable has to be a reference type, like UObject.
So using it as public and make it as UPROPERTY would be fine.

And I am afraid the UPARAM(ref) like above gonna change the output reference to input reference. So…

On the Blueprint node it will show as an input, yes.
But if the case is you really want an output pin on the node (not really needed imo) you can then add an out pin, like for example:

Anyway… I think what he really wants is a custom “Getter” function :slight_smile:

The “BlueprintGetter” specifier

Yeah, a getter sounds about right.
The thing is that the array is declared in a parent class. When its introduced, its supposed to be private, but some descendant classes are supposed to publish it for full outside access. For the “lower” classes, the member should stay private.
So putting it as a public property to begin with is not realy an option…

In this case you should use specialized methods to read/manipulate the array instead of returning a reference to the array, like mentioned. For example, the PrimitiveComponent class has methods called GetNumMaterials() and GetMaterial(int index) to access the internal array of materials without exposing it (in this case, it’s different from your case because the base class is “abstract” does not actually have an material array: it’s the descendant classes that may or may not have the ability to store materials).