Destroying an Actor with Cast results in crash

Hi,

I tried checking if the casting was
nulled and destroyItem() wouldn’t run
at all. So I’m guessing it might be
that

if you try executing destroyItem() on a nullptr, engine will crash. Since it wouldn’t run if you check that OverlappedCharacter is not nullptr, that means that the cast fails, so Other2Actor is not of type AItemKey. If the cast fails, then OverlappedCharacter will be nullptr

Hello, I’m trying to destroy an item in C++ using cast. Those are 2 separate CPP files, when I try running destroyItem() using the cast, the engine crashes.

ANewFile.h contains this :

   AActor * Other2Actor;

ANewFile.cpp

   AItemKey* OverlappedCharacter = Cast<AItemKey>(Other2Actor);
	OverlappedCharacter->destroyItem();

ItemKey.cpp

    void AItemKey::destroyItem() 
    {
       Destroy();
    }

Hope I made myself clear, bottom line is, the engine crashes everytime destroyItem(); is ran, and I don’t know why, did I do the casting wrong? I tried checking if the casting was nulled and destroyItem() wouldn’t run at all. So I’m guessing it might be that, if anyone can help that’d be great, thank you.

I see, so how can I make Other2Actor of type AItemKey, or make it work, not sure which of these really applies, I’m still new to all of this so sorry if that’s a silly question, thanks.

so how can I make Other2Actor of type
AItemKey

you can’t. It either is an AItemKey or it isn’t.

or make it work

If you expect Other2Actor to be of type AItemKey, then something is not working as you expect were you set it.


Declaring AActor* Other2Actor is not a good idea, better do AActor* Other2Actor = nullptr, otherwise it might not be nullptr but random garbage (isn’t your problem here, AFAIK it is just generally bad not to initialize pointers). Also if you never actually set Other2Actor to point to an actual AItemKey, then the cast will always fail, so what you need to solve this, is to set Other2Actor to point to an valid AItemKey object.

Got it working, once the object was valid I had no more issues, thank you! :slight_smile: