UEC++巧用ensure
大家在由蓝图开发转换到c++开发的时候,一定都遇到过这样一个问题:运行游戏,由于代码中某个指针为空,直接崩溃,但是我们不知道哪里为空。
那么有没有一种办法,当我运行游戏的时候如果出现了指针空错误的时候,能够自动定位到呢?
还真有,下面,我们介绍ensure、ensureAlways的用法
我们先以下面的代码片段举例
FVector playerLocation;
ACharacter* Text= Cast<ACharacter>(GetController()->GetCharacter())//获取角色
playerLocation=Text->GetActorLocation();//获取角色位置
上面的语句中在我们获取角色之后我们获取角色的位置,但是,如果Text获取失败了,那么是不是就发生空指针错误了。
加if判断
FVector playerLocation;
ACharacter* Text= Cast<ACharacter>(GetController()->GetCharacter())//获取角色
if(Text)
{
playerLocation=Text->GetActorLocation();//获取角色位置
}
很明显,空指针错误已经解决了。但是,如果text是空指针,因为你加了判断。那么playerLocation就拿不到值,如果你后面要用playerlocation变量的时候就会发生一些出乎你意料之外的错误。等debug一通之后,才发现:哦,原理是playerLocation没有拿到值!
用ensure
FVector playerLocation;
ACharacter* Text= Cast<ACharacter>(GetController()->GetCharacter())//获取角色
if(ensure(Text))
{
playerLocation=Text->GetActorLocation();//获取角色位置
}
当面我们运行到if语句时,如果此时Text为空,那么游戏不会崩溃,他会自动打开代码提示我们,这里是空的,但是每次打开UE只会提醒一次,意思就是:我已经提醒你了,如果你想要的逻辑是:拿到值就继续,不然就不执行,那你可以不改,如果逻辑是:必须要拿到值才能进行下去,那你就要检查你的代码,保证他能拿到值了。
用ensureAlways
FVector playerLocation;
ACharacter* Text= Cast<ACharacter>(GetController()->GetCharacter())//获取角色
if(ensureAlways(Text))
{
playerLocation=Text->GetActorLocation();//获取角色位置
}
每次运行到这里,如果为空就必定要弹出vs提醒。
是ensureMsgf会打印信息
需要注意的是,并不是每个变量都需要加ensure判断,因为有些逻辑就是:真进行这一步逻辑、假进行另一步逻辑。