How to Use FindObjectOfType in Unity: Simple Guide
In Unity, use
FindObjectOfType<T>() to find the first active object of type T in the scene. It returns the component if found or null if none exists. This method is useful for quick access but should be used sparingly for performance reasons.Syntax
The basic syntax of FindObjectOfType is:
T: The type of component you want to find (e.g.,Camera,PlayerController).FindObjectOfType<T>(): Returns the first active object of typeTfound in the scene.- Returns
nullif no object of typeTexists.
csharp
T foundObject = FindObjectOfType<T>();
Example
This example shows how to find a Light component in the scene and turn it off when the game starts.
csharp
using UnityEngine; public class LightController : MonoBehaviour { void Start() { Light sceneLight = FindObjectOfType<Light>(); if (sceneLight != null) { sceneLight.enabled = false; Debug.Log("Light found and turned off."); } else { Debug.Log("No Light component found in the scene."); } } }
Output
Light found and turned off.
Common Pitfalls
- Performance:
FindObjectOfTypesearches the whole scene and can slow down your game if used often, especially inUpdate(). - Returns only one object: It finds the first active object only, so if multiple objects of the type exist, others are ignored.
- Null checks: Always check if the result is
nullbefore using it to avoid errors.
csharp
using UnityEngine; public class WrongUsage : MonoBehaviour { void Update() { // BAD: Calling FindObjectOfType every frame hurts performance Light light = FindObjectOfType<Light>(); if (light != null) { light.enabled = true; } } } // Correct approach: Cache the reference once public class RightUsage : MonoBehaviour { private Light cachedLight; void Start() { cachedLight = FindObjectOfType<Light>(); } void Update() { if (cachedLight != null) { cachedLight.enabled = true; } } }
Quick Reference
Remember these tips when using FindObjectOfType:
- Use it to find one active component of a type in the scene.
- Always check for
nullbefore using the result. - Cache the result if you need to use it repeatedly.
- Avoid using it inside
Update()or frequently called methods.
Key Takeaways
Use FindObjectOfType() to get the first active component of type T in the scene.
Always check if the returned object is null before using it to avoid errors.
Cache the found object if you need to use it multiple times to improve performance.
Avoid calling FindObjectOfType frequently, especially inside Update(), to prevent slowdowns.