unity : transform.find : null

why this is wrong

unityで、子Objectを探し、見つかった場合と、見つからなかった場合で処理を分岐したい時があります。しかし、以下のcodeでは例外でstopしてしまします。

GameObject productContainer; // parent Object that contains several (or null) children
GameObject item;
item = productContainer.transform.Find("product1").gameObject;
if (item == null){
    // this code is never reached - if "product1" does not exist an exception is thrown
    Debug.Log("Not found");
}else{
    Debug.Log("Found"); // this code works if "product1" exists
}

Answer

上記の間違いは、以下の一文です。

item = productContainer.transform.Find("product1").gameObject;

productContainer.transform.Find("product1") == nullの時、
null.gameObjectがcallされてしまうため、ここで例外が発生しているのです。

正解は、こちら

GameObject item;
Transform tmp = productContainer.transform.Find("product1");

if (tmp == null)
    Debug.Log("Not found");
else
{
    item = tmp.gameObject;
    Debug.Log("Found");
}

参考URL

transform.find exception if child does not exist

もしよろしければ、サポートをお願いします! 頂いたサポートは、Creatorとしての活動費に充てさせて頂きます。