How to use FindComponentByClass?

I’m trying to create a quest system and I’m using a C++ component called Interact. The Interact function itself is supposed to do this:

When f is pressed

Search for the first actor within reach

Test if that actor has the CanBeInteractedWith component

If so, do whatever it’s quest is

If not, display the “there is nothing to interact with here” widget

I can’t find any tutorials online on how to search for something within reach or how to use the FindComponentByClass (or is there a different function I should be using?). I would really appreciate it if someone could help me out or even just point me towards a C++ tutorial like this.

Thanks in advance!

I’m trying to use C++, not blueprints.

Aside from your question, if you want to do a course that is paid, try Udemy, this is a well-rated course by an xUE4 employee. It goes on sale for under 10 bucks often.

More than one way to do this.

I personally would probably look at using Interfaces for this. It’s a pretty good use case for it. You can find all actors in a radius and check which ones implement the QuestGiving/Interactable interface. But might not work for you depending on how far along you are and your quest architecture. Just throwing it out there.

Ok to answer your question:

Find Actors

An easy way is to have a collision sphere around your character. When you’re ready call GetOverLappingActors (Get Overlapping Actors | Unreal Engine Documentation)

Searching your way

I’ve never used it but it’d be something like:

TArray<AActor*> OverlappedActors;

//get those actors here
....

for (AActor* potentialQuestGiver : OverlappedActors)
{
    UInteractableComponent* component = 
   potentialQuestGiver ->FindComponentByClass<UInteractableComponent>()

    if(component)
    {
        //do your thing
    }
      
}

I’ve actually already done a couple on Udemy, but I’m not trying to make a multiplayer game.

He teaches more than just multiplayer stuff in it. I haven’t finished it yet but I just thought that this might be useful to you since you mentioned that you couldn’t find any tutorials.

What does FindComponentByClass return, a boolean? And what is it that makes “component” work like a boolean even though it’s derived from a C++ class?

FindComponentByClass returns a “pointer” to a component. You can check it like a boolean value to see if it’s valid. If you use a non valid pointer your game will crash.

https://www.learncpp.com/cpp-tutorial/6-7a-null-pointers/

Judging by your question you’re very new to C++. I highly recommend taking some time and learn C++ basics through a good book. I prefer books as I’m old but I generally find they teach better. There are some really good lectures on Youtube too. Go find something that gels with you. I know it’s boring but I promise your time with UE4 will be so much better. You’ll also have a very employable skill.