More than one object in TArray causes crash

Developing a tycoon game which will have various interactable objects that are governed by one master C++ file. Each of these will have one of 4 needs which can be met, set via an enum when spawned.

The code below works perfectly when there’s only one of these interactables in a scene but as soon as I place even a second, UE4 crashes.

Here’s the code:

				FOutputDeviceNull ar;
				this->CallFunctionByNameWithArguments(TEXT("CheckValidInteractables"), ar, NULL, true);
				TArray<AActor*> FoundActors;
				UGameplayStatics::GetAllActorsOfClass(GetWorld(), ClassToFind, FoundActors);

				int32 NumOfNeedMatchingInteractables = 0;

				if (FoundActors.Num() > 0)
					int32 CountUpTo = FoundActors.Num() - 1;
					for (int32 i = 0; CountUpTo; i++)
						AInteractablesMaster* ThisInteractable = Cast<AInteractablesMaster>(FoundActors[i]);
						if (ThisInteractable)
							uint8 ThisNeedMetAsInt = uint8(ThisInteractable->NeedMetOne);
							if (BiggestNeed == ThisNeedMetAsInt)
								NumOfNeedMatchingInteractables += 1;
					UE_LOG(LogTemp, Warning, TEXT("Numbers matching need: %i"), NumOfNeedMatchingInteractables);
					UE_LOG(LogTemp, Warning, TEXT("No valid actors found"));

I get this error message: Assertion failed: (Index >= 0) & (Index < ArrayNum) but surely as I’m only telling it to count to 1 less than than the total Num in the array, it should never get this far.

I can’t help but think I’m missing something obvious but I honestly don’t know what that could be right now.

Any thoughts or ideas on what I can do?

Thanks in advance.

The 2nd argument of for should be loop condition which needs to be bool. Compiler interprates int to bool, so 0 = false anything is else is true, so since you place integer you gonna have infinite loop in any case other then CountUpTo = 0 (then it won’t loop at all since it will be permanently false). So you should do proper bool statement like this like you do in if statment:

for (int32 i = 0; i < CountUpTo; i++)

Also since C++11 there special for each loop for arrays so you don’t need to do manual counting (or else you need count number), all you need to do is:

for(AActor* Actor : FoundActors)

and loop will loop thru all elements of array and set Actor variable a current looped element of array. This will help you avoid any counting issues… as you don’t need to count anything ;p

Perfect! Thank you.