I wanted to share with the community a huge bug I found. I filed a case for it but I don’t expect to be fixed because it is so fundamental it would affect existing projects. I’m sharing it here so others will know to be on the lookout.
According to the documentation Unity - Scripting API: Component.GetComponentInParent
“Returns the component of Type type in the GameObject or any of its parents.”
While this IS the case with scene objects, it is NOT the case with assets. GetComponentInParent will fail to find the component if it is on the same object when it is assets.
I’ve attached a script that shows the issue. If you add a Rigidbody to an object, the script will pass if the object is in the scene, but fail as an asset.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
static public class GetComponentInParentBug
{
[MenuItem("GameObject/3D Object/GetComponentInParentTest/Test")]
private static void TestFromScene()
{
GetComponentInParentBugTest();
}
[MenuItem("Assets/GetComponentInParentTest/Test", false)]
private static void TestFromProject()
{
GetComponentInParentBugTest();
}
private static void GetComponentInParentBugTest()
{
UnityEngine.Object[] selectedObjects =
Selection.GetFiltered(typeof(UnityEngine.GameObject), SelectionMode.Assets);
foreach (GameObject selectedObject in selectedObjects)
{
Rigidbody parentRb = selectedObject.GetComponentInParent<Rigidbody>();
Rigidbody thisRb = selectedObject.GetComponent<Rigidbody>();
if (parentRb == null && thisRb != null && thisRb.gameObject == selectedObject)
{
Debug.LogError("GetComponentInParent<Rigidbody>() failed but GetComponent<Rigidbody>() succeeded on the same object!", selectedObject);
}
else
{
Debug.Log("All is good", selectedObject);
}
}
}
}