issues with AddUnique and arrays

This is giving me errors only when i add CharacterHitResult.AddUnique(HitCharac)

TArray<FHitResult> HitResult;

TArray<AShooterCharacter> CharacterHitResult;

for (const FHitResult& LoopHitResult : HitResult)
{

	AShooterCharacter* HitCharac = Cast<AShooterCharacter>(LoopHitResult.Actor);

	CharacterHitResult.AddUnique(*HitCharac);
}

TArray requires Type (AActor in this case) to be publicly copy constructible (public T(const T&) constructor), whereas AActors copy constructor is private. On top of that, AddUnique requires operator==(const T&) const to be defined, which AActor doesn’t have.

Apart from that, by dereferencing a pointer when adding it to an array, you would be creating a copy of the pointed object, thus the object in the array would not be the same that you added (well, it would be a copy of it, but it would no longer be the same object).

I would recommend changing the type of the TArray from AShooterCharacter to AShooterCharacter* and storing a pointer to that object CharacterHitResult.AddUnique(HitCharac);

1 Like

thanks that fixed that BUT it also caused some problems bellow

the error is cant convert ShooterCharacter* to ShooterCharacter

for (const AShooterCharacter& ShooterCharRef : CharacterHitResult)
{
	FString PlayerName = ShooterCharRef.GetActorLabel();

	GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Yellow, PlayerName);
}

In the code above you are trying to assign a pointer to a reference. You could do a reference to a pointer, but in this case it would be rather pointless. I recommend changing the type of ShooterCharRef to a pointer to AShooterCharacter. Before using it, it’s wise to check if the object is still valid and we are not dereferencing a tangling pointer (unless you are 100% sure it wasn’t deleted). Also note, that GetActorLabel function is only available in development builds, so I reckon that it won’t compile in cooked builds.

for (const AShooterCharacter* const ShooterChar : CharacterHitResult)
 {
     if(!IsValid(ShooterChar))
     {
          continue;
     }

     const FString& PlayerName = ShooterChar->GetActorLabel(); // or e.g. ShooterChar->GetName();
     GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Yellow, PlayerName);
 }