Referencing components from a blueprint in c++

image
I’ve been having an issue where I’m having trouble finding out how I can reference a component (example here of a spiring arm) from a blueprint. Anyone know how this can be achieved?

So your blueprint class has a spring arm and this needs to be accessed from c++ right?

If you have actor reference already and have one component below should work already, more than one component think FindComponents should work too.

 spring = ActorRef->FindComponentByClass<USpringArmComponent>();

I have tried this but it returns a nullpointer, maybe I have been doing something wrong?

If your target actor is self (this), then it means your blueprint is derived from same class?

You have a AMyCharacterClass or actor which has a spring variable defined, you can add component in constructor already, if you want can pinpoint you to that direction.

springarm= CreateDefaultSubobject<USpringArmComponent>(TEXT("MySpringArm"));

You don’t have to add the component from the blueprint already however if you add and use

spring  = FindComponentByClass<USpringArmComponent>();

It shouldn’t be null at all. I suspect your TargetActor is not “This” .. if they are same you can just create a subobject already.

Are you sure that your actor (class reference) is “this”, try accessing your actor like below

		TSubclassOf < AActor > ActorClass;
		AActor*  TargetActor = UGameplayStatics::GetActorOfClass(GetWorld(), ActorClass);
		if (TargetActor)
		{
			USpringArmComponent*  spring = TargetActor->FindComponentByClass<USpringArmComponent>();
			if (spring)
			{
				UE_LOG(LogTemp, Warning, TEXT("Found Spring Arm at target actor"));
			}
			else
			{
				UE_LOG(LogTemp, Warning, TEXT("Cannot access spring arm on target Actor"));
			}
		}
		else
		{
			UE_LOG(LogTemp, Warning, TEXT("No Actor Found"));
		}
	}

Just be sure that target actor is right and has already a spring arm assigned.
Welcome to the forums btw, let me know your further questions around it.

1 Like

I was trying to mimic unity in where you could declare a public camera object and then select the camera outside of the script, but I think I might just go with the create default sub object.

actually figured it out right after posting this

1 Like