无法找出我自己的自定义异常

时间:2016-04-28 12:11:26

标签: c# exception unity3d unity5

我有这个尝试catch块。我写自己的例外比较新,所以要纠正我做错的事。现在我的问题是我想知道是否缺少两件事之一并将该名称传递给我的例外。但在我可以做任何检查之前,我似乎已经退出了尝试。这是代码:

error 500: Invalid state

我要检查的两件事是childSprite和spriteAnimator。

2 个答案:

答案 0 :(得分:4)

您应该将编码更改为以下内容,并对正确的异常/组件名执行空检查:

string componentName = "";

if (Constants.AllowedTyleTypes.Contains(currentTile.tyleType))
{
    if (currentTile.transform.FindChild("Sprite") == null || currentTile.transform.FindChild("Sprite").gameObject == null)
    {
        throw new MissingComponentsForAnimationException("childSprite", currentTile.name);
    }

    GameObject childSprite = currentTile.transform.FindChild("Sprite").gameObject;

    Animator spriteAnimator = childSprite.GetComponent<Animator>();
    if (spriteAnimator == null)
    {
        throw new MissingComponentsForAnimationException("spriteAnimator", currentTile.name);
    }

    spriteAnimator.SetBool("PassedBy", true); 
}

答案 1 :(得分:0)

在您的代码中,您试图捕获System.Exception,而根据您的说法,您实际上想要抛出MissingComponentsForAnimationException

如果childSprite或spriteAnimator为null,下面的代码将抛出您想要的异常。然后由您决定处理它们。

if (Constants.AllowedTyleTypes.Contains(currentTile.tyleType))
    {
        GameObject childSprite = currentTile.transform.FindChild("Sprite").gameObject;

        if (childSprite == null)
            throw new MissingComponentsForAnimationException("childSprite", currentTile.Name);

        Animator spriteAnimator = childSprite.GetComponent<Animator>();

        if (spriteAnimator == null)
            throw new MissingComponentsForAnimationException("spriteAnimator", currentTile.Name);

        spriteAnimator.SetBool("PassedBy", true);
    }
相关问题