Why is FindObjectOfType(MyType) not finding anything?

Why would I get the following log?

  • Start OpponentMotionReceiver
  • motion receiver not found
  • true

    public class ScoreAnimation : MonoBehaviour
    {
        private OpponentMotionReceiver cachedObject;

        private void Start()
        {
            cachedObject = FindObjectOfType<OpponentMotionReceiver>();
        }

        private void OnDestroy()
        {
                var motionReceiver = FindObjectOfType<OpponentMotionReceiver>();

                if (motionReceiver == null)
                {
                    Debug.Log("motion receiver not found");
                }
                 
                if(cachedObject != null)
                {
                    //prints true, another proof that the gameObject is active
                    Debug.Log(cachedObject.gameObject.activeInHierarchy);
                }
        }
    }

public class OpponentMotionReceiver : MonoBehaviour
    {
        private void Start()
        {
            Debug.Log("Start OpponentMotionReceiver");
        }

        private void OnDisable()
        {
            //never enters
            Debug.Log("OnDisable OpponentMotionReceiver");
        }

        private void OnDestroy()
        {
            //never enters
            Debug.Log("OnDestroy OpponentMotionReceiver");
        }
    }

P.S. This is extremely simplified version of the code so that the rest brings no confusion. If you need more details, I’d be pleased to answer you!

Changing the scene. Only at that time unity behaves like that. No matter if the object we are looking for is active or not, simply FindObjectOfType doesn’t work at this point of the game cycle.

From unity - Why is FindObjectOfType(MyType) not finding anything? - Game Development Stack Exchange

Easy :slight_smile:

var motionReceiver = FindObjectOfType<OpponentMotionReceiver>();

Will return null when:

  1. No one initialized OpponentMotionReceiver component present.
  2. All “Objects who contains” OpponentMotionReceiver component now in state = disabled.

59702-1.png

59703-2.png