// Called when the game starts or when spawned
void ASonicCharacterComponent::BeginPlay()
{
Super::BeginPlay();
if (SonicCameraComponent && SpringArmComponent && SonicCameraComponent->Camera->GetCameraComponent())
{
SonicCameraComponent->SetupCamera(this, SpringArmComponent, SonicCameraComponent->Camera);
}
else
{
UE_LOG(LogTemp, Error, TEXT("ASonicCharacterComponent::BeginPlay - Missing required components"));
}
}
void ASonicCharacterComponent::StatusHandler()
{
if (!SonicMovement) return;
code
float CurrentSpeed = SonicMovement->GetForwardSpeed();
bool bIsFalling = SonicMovement->IsFalling();
constexpr float MovementThreshold = 1.0f;
//print current state, and current speed
GEngine->AddOnScreenDebugMessage(-1, 0.0f, FColor::Red, FString::Printf(TEXT("Current State: %s"), *UEnum::GetValueAsString(CurrentState)));
GEngine->AddOnScreenDebugMessage(-1, 0.0f, FColor::Red, FString::Printf(TEXT("Current Speed: %f"), CurrentSpeed));
if (CurrentSpeed > MovementThreshold && CurrentState == EFEeSonicCharacterState::Idle)//if idle then set to moving
{
if (CurrentState != EFEeSonicCharacterState::MovingOnGround)
{
CurrentState = EFEeSonicCharacterState::MovingOnGround;
}
}
//if we are in ground movement state, but we stand still, set to idle
else if (CurrentSpeed <= MovementThreshold && CurrentState == EFEeSonicCharacterState::MovingOnGround)
{
CurrentState = EFEeSonicCharacterState::Idle;
}
//if we are in ground movement, but we are in the air, set to falling
if (CurrentState == EFEeSonicCharacterState::MovingOnGround && GetCharacterMovement()->IsFalling())
{
CurrentState = EFEeSonicCharacterState::Falling;
}
//if the state we are currently in is listed as an in air state, but we are no longer in the air, reset to idle
if (StateInAir() && !GetCharacterMovement()->IsFalling())
{
CurrentState = EFEeSonicCharacterState::Idle;
}
}
bool ASonicCharacterComponent::StateInAir()
{
//if the state is either jumping or falling, return true
if (CurrentState == EFEeSonicCharacterState::Jumping ||
CurrentState == EFEeSonicCharacterState::Falling ||
CurrentState == EFEeSonicCharacterState::HomingAttacking||
CurrentState == EFEeSonicCharacterState::AirBoosting||
CurrentState == EFEeSonicCharacterState::AirDashing)
//don't include light speed dashing because we want to be able to dash from the ground
{
return true;
}
return false;
}
// Called every frame
void ASonicCharacterComponent::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
StatusHandler();
FancyArrow->SetWorldLocation(GetActorLocation());
}
AUnleashedCamera::AUnleashedCamera()
{
PrimaryActorTick.bCanEverTick = true;
bLookAtSonic = false;
//get camera actor
RootComponent = GetCameraComponent();
}
void AUnleashedCamera::BeginPlay()
{
Super::BeginPlay();
//find sonic
SonicCharacter = Cast(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
if (!SonicCharacter)
{
UE_LOG(LogTemp, Error, TEXT("SonicCharacter not found in camera"));
}
}
void AUnleashedCamera::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (bLookAtSonic)
{
LookAtTarget(SonicCharacter);
}
code
switch(CameraType)
{
case EUnleashedCameraType::SplineCamera:
UpdateSplineCamera(DeltaTime);
break;
case EUnleashedCameraType::FollowCamera:
UpdateFollowCamera(DeltaTime);
break;
default:
break;
}
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class SONICUNLEASHEDREMAKE_API USonicCameraComponent : public UActorComponent
{
GENERATED_BODY()
public:
USonicCameraComponent();
code
// Initializes the camera with the given parameters
void SetupCamera(AActor* InOwner, USpringArmComponent* InSpringArm, AUnleashedCamera* InCamera);
// Sets the camera boom length dynamically
void SetCameraBoomLength(float Distance);
void ResetCamera(float DeltaTime);
ACharacter* Character = Cast<ACharacter>(OwnerActor);
if (!Character) return;
FVector Velocity = Character->GetVelocity();
Velocity.Z = 0.0f;
float Speed = Velocity.Size();
FVector CharacterForward = Character->GetActorForwardVector();
FVector CameraForward = Camera->GetActorForwardVector();
float DotProduct = FVector::DotProduct(CharacterForward, CameraForward);
const float MarginFacingTowards = 0.85f; // Smaller margin when facing towards the camera
const float MarginFacingAway = 0.95f; // Larger margin when facing away from the camera
// Determine which margin to use
float EffectiveMargin = DotProduct < 0 ? MarginFacingTowards : MarginFacingAway;
// Trigger camera reset only if speed is above threshold and Sonic is not facing directly towards or away
if (Speed > SpeedThresholdForCameraReset && FMath::Abs(DotProduct) < EffectiveMargin)
{
ResetCamera(DeltaTime);
}
The error you're encountering is due to attempting to access a null pointer in your ASonicCharacterComponent constructor. Specifically, you're trying to access SonicCameraComponent->Camera before it has been initialized, which leads to a crash.
Here's what's happening:
In your constructor ASonicCharacterComponent::ASonicCharacterComponent, you have the following lines:
At this point, SonicCameraComponent->Camera is nullptr because it hasn't been assigned a valid value yet.
Attempting to call GetCameraComponent() on a nullptr results in a crash.
How to fix it:
Avoid Accessing Uninitialized Pointers in the Constructor:
You should not access SonicCameraComponent->Camera in the constructor because it hasn't been initialized yet. Remove or comment out the lines in the constructor where you access Camera:
cpp
// Remove these lines from the constructor
// SonicCameraComponent->Camera->GetCameraComponent()->SetupAttachment(SpringArmComponent);
// SonicCameraComponent->Camera->GetCameraComponent()->bUsePawnControlRotation = false;
Initialize the Camera Pointer in BeginPlay:
Move any code that depends on SonicCameraComponent->Camera to the BeginPlay method, where you can ensure that Camera has been properly initialized.
Assign the Camera Pointer:
You need to make sure SonicCameraComponent->Camera is assigned a valid instance of AUnleashedCamera. You can do this by spawning a new camera actor or finding an existing one in the level.
Here's how you can modify your BeginPlay method:
cpp
void ASonicCharacterComponent::BeginPlay()
{
Super::BeginPlay();
// Ensure SonicCameraComponent is valid
if (SonicCameraComponent)
{
// Assign the Camera if it's not already set
if (!SonicCameraComponent->Camera)
{
// Try to find an existing UnleashedCamera in the level
SonicCameraComponent->Camera = Cast<AUnleashedCamera>(UGameplayStatics::GetActorOfClass(GetWorld(), AUnleashedCamera::StaticClass()));
if (!SonicCameraComponent->Camera)
{
// If not found, spawn a new one
SonicCameraComponent->Camera = GetWorld()->SpawnActor<AUnleashedCamera>(AUnleashedCamera::StaticClass());
}
}
// Now that Camera is valid, set up the attachment
if (SpringArmComponent && SonicCameraComponent->Camera && SonicCameraComponent->Camera->GetCameraComponent())
{
// Attach camera component to SpringArm
SonicCameraComponent->Camera->GetCameraComponent()->SetupAttachment(SpringArmComponent);
SonicCameraComponent->Camera->GetCameraComponent()->bUsePawnControlRotation = false;
// Now call SetupCamera
SonicCameraComponent->SetupCamera(this, SpringArmComponent, SonicCameraComponent->Camera);
}
else
{
UE_LOG(LogTemp, Error, TEXT("ASonicCharacterComponent::BeginPlay - Missing required components"));
}
}
}
Ensure Safe Access to Pointers:
Always check if a pointer is valid before accessing its members. This prevents null pointer dereferences. For example:
cpp
if (SonicCameraComponent && SonicCameraComponent->Camera)
{
// Safe to access SonicCameraComponent->Camera
}
Consider Design Adjustments:
Depending on your game's design, it might be better to:
Assign the Camera via the Editor: If the Camera is intended to be set in the editor, make sure to assign it in the Blueprint derived from ASonicCharacterComponent.
Refactor Component Initialization: If possible, consider initializing components such that their dependencies are resolved during or after BeginPlay, not in the constructor.
Update Your Component's Initialization Logic:
Since the Camera is of type AUnleashedCamera, which is an actor, you cannot create it as a subobject in the constructor. Actors need to be spawned in the world. By spawning or finding the camera actor in BeginPlay, you ensure that it exists before you attempt to use it.
Avoid Spawning Actors in Constructors:
Spawning actors in constructors is not allowed in Unreal Engine. Always spawn actors in a function like BeginPlay or another appropriate method that's called after the world has been initialized.
Summary:
Do not access uninitialized pointers in constructors.
Initialize your camera actor (AUnleashedCamera) in BeginPlay.
Move any code that depends on the camera to BeginPlay or later.
Ensure safe pointer access by checking for nullptr before usage.
By following these steps, you should resolve the crash and ensure that your camera component is properly initialized and used safely in your character class.