It seems that this method is pretty common to use in blueprint casting and I’d like to know what are the pros and cons to it, like is it the standard method or is there a better way to go about it? Wouldn’t it get stuck in a loop if there was a permanent issue casting?
Hey, Haven’t seen it done like this before, but pretty sure they’ve done this to get round the instantiation sequence/delays of the core ue4 classes… Basically UE4 creates an instance of each of your core objects in sequence at start up… I can’t remember the exact order, but seem to remember it’s something along the lines of: Game Instance, Player Controller, Player State, Game Mode, Game State. So you can have Game Instance having been created and having run it’s Constructor and Event Begin Play before the Player Controller has been instanced. So if you try to get a reference to the Player Controller in the Game Instance Begin Play it will return cast failed as it doesn’t exist yet.
So the delay loop basically carries on looping until the Game Instance has been created and returns a valid reference.
I have something similar in my code, except I have an “Initialised” boolean that is checked at the beginning of every Event Tick, that while false continues checking for the valid status of some of the other objects I need a reference for until they’ve been instanced/are valid…
Personally. I find these sort of things not only bad but also a lazy solution. Don’t get me wrong, it’s good as a temporary quick fix, but as we all know, “temporary” usually ends up as “permanent”.
Ah okay, thanks for letting me know!
FWIW I often use something similar: (IsValid node checks).
Its maybe a tiny / small saving on resources versus casting…
Its more complex than that because of PIE vs Packaging…
Plus there’s also unique differences due to Multiplayer too.
Feel free to share robust solutions dude as we’d all benefit… :)
There is no reason why you would want to set the reference on BeginPlay or even save the reference in the first place since it will not solve any run-time null pointer errors anyway without checking if the reference is null when using it.
Simply make a function that GetGameInstance and casts it and return the reference. It is rarely necessary to save a reference into a variable although that is what every tutorial out-there tells you to do even for simple logic.
If you really want to save a reference then make a function that returns the variable if valid or GetGameInstance and set the variable then return it if not valid. There is no need for silly delay loops.