Download

Calling UActorcomponent method from another class

Hi !
I’m currently learning how to use the UE4 c++ library with basic c++ knowledge.
The issue is that I have a Pawn class, wich I want it to call a function from another actorComponent but i get that message in UE4 editor :
LogUObjectGlobals:Warning: Class which was marked abstract was trying to be loaded. It will be nulled out on save. None ActorComponent

Obviously I should have use an actor class for it to work, but I would like to know if it’s still possible to do it with an actorComponent.

The peice of code basically looks like that.

Chibijoke.cpp

void AChibiJoke::Fire()
{
UActorComponent* Weapongear = NewObject<UActorComponent>();
UWeaponSystem * const Weapon = Cast<UWeaponSystem>(Weapongear);
if (Weapon)
{
Weapon->Firing();
}
else
{
UE_LOG(LogTemp, Warning, TEXT(" Not Firing "));
}
}
Weaponsystem.cpp

void UWeaponSystem::Firing()
{
UE_LOG(LogTemp, Warning, TEXT(" Firing "));
}

I would aslo like to know if theire is simpler ways to call function from another class and specifically actorcomponent functions.

I’m quite new to this myself, but I think I can help a bit

Firstly looking at your code:


UActorComponent* Weapongear = NewObject<UActorComponent>();
UWeaponSystem * const Weapon = Cast<UWeaponSystem>(Weapongear);

The first line won’t work because UActorComponent is marked as an abstract class i.e. it cannot be instantiated itself, only classes which derive from it (e.g. your UWeaponSystem), so that is the cause of your error.

Ignoring the issue in the first line, I’m pretty sure the second line would only work if Weapongear pointed to an object of type UWeaponSystem or a child of UWeaponSystem. Weapongear can still be declared as UActorComponent*, but the actual object instance it points to needs to be UWeaponSystem if that’s what you’re casting to.

So I think those lines might become something like this, assuming you want to create the Component at runtime and attach it to your ChibiJoke actor


UWeaponSystem* Weapon = NewObject<UWeaponSystem>(this, FName("MyWeaponSystem"));
Weapon->RegisterComponent();

Weapon->Firing();


Alternatively, if you have already attached a WeaponSystem component to your actor, either in the editor (e.g. created a blueprint derived from AChibiJoke and attached WeaponSystem component in the blueprint), or previously in the C++ class, you can access the component by using


UWeaponSystem* Weapon = this->**FindComponentByClass<UWeaponSystem>();**
if (Weapon)
    Weapon->Firing();

Hi !
Thanks for the reply, I was looking for doing a none abstract child class. Your comment totaly comfirmed it and was very helpfull !
I’ll give it a try !

Hi ! I tried what you mentioned Simtbi, and it works ! I’v been so consfused with thta issue. Thanks a lot for the help, now my code works properly.