Hello guys. I’m newcomer in UE4 and have a question. I’m trying to make my character “hide behind a partition” and wrote a code for it, but when I’m pressing the button for this action the game is crashing. This is my code:
A crash in this situation is likely to be due to your Character not being valid. It is good practice to check the validity of pointers you are using. Especially in cases when you are casting, you want to ensure the cast has failed.
You can do things like:
if (AMainChar_C* Char = Cast<AMainChar_C>(GetOwner()))
{
// Your logic here, only executing if the Character was successfully cast
}
If this stops it from crashing, this probably means the cast was failing - so your next task would be to find out why that is.
My rule is generally if I am ever dereferencing a pointer (MyPointer->Something), I will ensure I’ve checked that MyPointer is not nullptr first.
check the error log and post info :). your i in the for loop is not initialized, and <= will get you the last index as Num() which is out of range since arrays start at index 0, not 1.
Should be:
If it’s initialized in the header, your call to CloseEnough will only work the first time. Or on subsequent calls it may skip checking a bunch of actors because your index is already 12 (for example) for 20 actors.
While there are cases where that sort of iteration makes sense, usually you would have the lifetime of an index be roughly the same as the collection it’s used on. At the very least, the lifetime of the collection should dictate the maximum lifetime of the index.
Do you know how to debug with Visual Studio? You could whack in a breakpoint at the if statement and follow it through to see at which point it is failing. If you never get to the GetAllActorsOfClass, then it means your cast is failing.
Alternatively you could use some UE_LOGs to find out which bits of the code are executing, but I’d highly recommend debugging. I’ve got a video on it on youtube, hoping there’s no issue with me sharing it here for you: https://www.youtube.com/watch?v=MmJW4tc5nIo