Something strange with arrays in C++ -> blueprint

I have a BlueprintPure C++ function that return a TArray. It generates two or three elements depending on randomness.

When I call it from blueprint, and then have a ForEach node, I - sometimes! - get the following error:

LogScript: Warning: Script Msg: Attempted to access index 2 from array ‘CallFunc_GenerateEncounterTimes_ReturnValue’ of length 2 in ‘/Game/Shared/Blueprint/UI/Transit/WBP_TransitScreen.WBP_TransitScreen_C:initializeBattleEvents’!
LogScript: Warning: Script Msg called by: WBP_TransitScreen_C /Engine/Transient.UnrealEdEngine_0:MyGame_C_30.WBP_TransitScreen_C_0

Regardless of whether it’s 2 or 3 elements, how could a ForEach node get this wrong?

TArray UTransitSubsystem::GenerateEncounterTimes() const
{
  constexpr auto minGap = 0.1f;
  constexpr auto halfGap = minGap / 2.0f;
  constexpr auto minTime = 0.15f;
  constexpr auto maxTime = 0.85f;

  TArray<float> times{};

  // Generate a sensible number of encounters.
  auto const count = generateEncounterCount(2,3);

  // Split the interval [0,1] into that many buckets and put an encounter at
  // a random point in each of these buckets. Have a margin so that all events
  // are at least minTime apart.
  auto const step = 1.0f / float(count);

  auto t = 0.0f;
  for (auto i = 0; i < count; ++i)
  {
  	  auto const lo = t + halfGap;
	  auto const hi = t + step - halfGap;
	  auto const s = FMath::RandRange(lo, hi);
	  ensure(s >= 0.0f && s <= 1.0f);
	  auto const time = minTime + s * (maxTime - minTime);
	  times.Add(time);

	  t += step;
  }

  return times;
}

sounds like the issue of a ‘pure’ node not the for each loop,

ie the pure node is recalled on each iteration returning different results.

Make it BlueprintCallable or cache the result before looping should fix it

1 Like

Sir, thou art a genius! Adding this to my big list of Unreal Gotchas :slight_smile: Merry Christmas!

1 Like