Using Delegates to set bDoorSoundPlaying

My code is a bit different as I’m using delegates with the pressure plate and the audio component:

void UOpenDoor::SetupAudioComponent()
{
	DoorSound = GetOwner()->FindComponentByClass<UAudioComponent>();
	if (!DoorSound)
	{
		UE_LOG(LogTemp, Error, TEXT("%s missing audio component"), *GetOwner()->GetName());
	}
	DoorSound->OnAudioFinished.AddDynamic(this, &UOpenDoor::OnDoorSoundStopped);
}

Then instead of bothering with the tick component which may have timing issues if your door is opening longer than the sound, I only trigger the sounds in the OnOverlapBegin/End:

void UOpenDoor::BeginPlay()
{
	Super::BeginPlay();
	InitialRotation = GetOwner()->GetActorRotation();
	CurrentRotation = InitialRotation;
	OpenAngle += CurrentRotation.Yaw;	

	if (PressurePlate)
	{
		PressurePlate->OnActorBeginOverlap.AddDynamic(this, &UOpenDoor::PlateOnOverlapBegin);
		PressurePlate->OnActorEndOverlap.AddDynamic(this, &UOpenDoor::PlateOnOverlapEnd);
	}
	else
	{
		UE_LOG(LogTemp, Error, TEXT("Pressure Plate on Actor: %s is not set"), *GetOwner()->GetName());
	}

	SetupAudioComponent();
}


void UOpenDoor::PlaySound()
{
	if (!DoorSound)
	{
		return;
	}
	bDoorSoundPlaying = true;
	DoorSound->Play();
}


void UOpenDoor::OnDoorSoundStopped()
{
	bDoorSoundPlaying = false;
}

void UOpenDoor::PlateOnOverlapBegin(class AActor* OverlappedActor, class AActor* OtherActor)
{
	if (!OtherActor)
	{
		return;
	}

	CurrentPressureMass += GetActorsMass(OtherActor);
	if (CurrentPressureMass > RequiredPressureMass)
	{
		bOpenDoor = true;
		PlaySound();
	}
}

void UOpenDoor::PlateOnOverlapEnd(class AActor* OverlappedActor, class AActor* OtherActor)
{
	if (!OtherActor)
	{
		return;
	}

	CurrentPressureMass -= GetActorsMass(OtherActor);
	if (CurrentPressureMass < RequiredPressureMass)
	{
		bOpenDoor = false;
		PlaySound();
	}
}
1 Like

Great job using delegates! How do you feel about them?

Good! As someone who does backend / systems development I’m very weary of executing anything in hot loops (which the TickComponent is). Although I understand why for this lecture they weren’t used!

Privacy & Terms