Unity: 在Awake()期间捕获抛出的异常。

huangapple go评论80阅读模式
英文:

Unity: Catch exception thrown during Awake()

问题

我有一个Unity项目,其中我动态实例化了一个预制件,而该预制件具有一个自定义脚本组件,在Awake()函数中进一步初始化该组件。在这一点上,初始化可能会失败,并且需要中止,这意味着当前游戏对象和被调用的对象都需要以某种方式通知。虽然销毁游戏对象没有问题,但优雅地通知调用者正在变得更加困难。

实例抛出的异常显示在Unity Console中,异常的堆栈跟踪还包括Instantiate调用,但尝试在具有Instantiate调用的行上捕获任何异常都不起作用。

如何在调用者的那一点上捕获异常,或者以其他方式使用内置功能来表示需要中止初始化?

附言:
我知道我可以让实例设置一个标志,并从调用者那里检查它,或者首先让Unity处理游戏对象的初始化,并在直接调用中处理我的初始化并捕获错误,但我希望有可能找到一个更好的解决方案。

英文:

I have a Unity project where I'm dynamically instantiating a prefab, and that prefab has a custom script component that further initializes the component during the Awake() function. At this point initizalization might fail and need to be aborted, which means that both the current game object needs to be destroyed, and the called needs to be notified in some way. While destroying the game object is no problem, elegantly notifying the caller is proving more difficult.

The exception thrown by the instance appears in the Unity Console, where the stack trace of the exception also includes the Instantiate call, but attempting to catch any exception on the line with the Instantiate call does nothing.

How can I catch an exception at that point in the caller, or otherwise use built-in functionality to signal that initialization needs to be aborted?

P.S.<br>
I Know I could let the instance set a flag and inspect that from the caller, or first let Unity handle initialization of the game object, and handle my initialization in a direct call and catch an error there, but I was hoping a nicer solution is possible.

答案1

得分: 2

Instantiate方法在内部捕获异常,因此您无法在外部捕获任何异常,必须在Awake消息中捕获它们,然后使用DestroyImmediate方法立即销毁实例。

void Awake()
{
    try
    {
        throw new System.Exception();
    }
    catch
    {
        DestroyImmediate(gameObject);
    }
}

通过使用这种方法,Instantiate方法可以抛出UnityException,您可以捕获它。

try
{
    Instantiate(prefab);
}
catch(UnityException)
{
    print("Instantiate prefab failed");
}
英文:

The Instantiate method catches exceptions internally, so that you cannot catch any exceptions outside, you must catch them inside the Awake message and then use the DestroyImmediate method to destroy the instance immediately.

void Awake()
{
	try
	{
		throw new System.Exception();
	}
	catch
	{
		DestroyImmediate(gameObject);
	}
}

By using this method, the Instantiate method can throw a UnityException which you are able to catch.

try
{
	Instantiate(prefab);
}
catch(UnityException)
{
	print(&quot;Instantiate prefab failed&quot;);
}

huangapple
  • 本文由 发表于 2023年7月13日 19:37:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定