Search code examples
arraysstructunreal-blueprintunreal-engine5

Adding a new Entry in a Struct holding a TArray as Member value doesn’t update it’s entries


I am currently working on a Character Customization System where a HUDLayout dynamically create Widgets based on a set of Skins available for the Character Selected. A Skin is represented as a Struct called MaterialInstanceContainer and holds a TArray. Player can mix and match their selection according to the Body Parts they select. In order to achieve the final result, I want to create a TMap<string, MaterialInstanceContainer> so that I can map each BodyParts available for selection with the individual material instance targeting the same BodyPart.

ISSUE: My issue is as follow, when I try to foreach over my collection of Material Instances inside my Container, I do a string comparison and if the output is valid, I can then break my struct to access the Material Instance Array and ADD to it however, at the very end of the process, the length of the array inside Material Container is still at zero.

How can I add a new entry in the array that my Material Container Struct hold?

Thanks! enter image description here


Solution

  • The issue here is actually pretty straight forward: in Blueprints when you 'Find' a member of Map you are not getting it by-reference, instead you get the copy.

    This is exactly what happens at the end of your nested loop: You get a copy, you add item to it, and when another iteration kicks-in the copy gets terminated.

    enter image description here

    And here on my side it returns exactly the same result as expected:

    enter image description here

    The fix for that would be easy:

    After editing a Copy, you can overwrite the Map member by its copy (via 'Add' node).

    But in your case it will be more tricky. You cannot just plug the same BreakStruct/Array node that you just used because it would call whole Find sequence again which creates another copy. Look

    enter image description here

    If you are confused. This code actually looks like this for Unreal's point of view.

    enter image description here

    So you have to store the the Struct in local variable first, then perform any operations on it and after everything is done - overwrite the Map member by its locally stored copy. And the result is

    enter image description here

    Map member gets overwritten every time and everything is as it should be.

    Well, almost... For some reason your code is stored in Macro. I think you have to change it to a Function to be able to create local struct variable. But it shouldn't be a problem in this specific case because in your code there is no logic that needs to be done in macro.

    Hope, it helps