Menu
CoddyTech

Find by Type

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 44 of 67.

GetComponent looks on one object. To find a component anywhere in the scene, search by its type: FindAnyObjectByType<T>() returns an active object of type T, or null when there is none. A level script that resets the scene's one Scoreboard finds it when the game starts:

private Scoreboard board;

void Start()
{
    board = FindAnyObjectByType<Scoreboard>();
    board.ResetScore();
}

The search works for your own scripts and for Unity's components alike: FindAnyObjectByType<Camera>(), FindAnyObjectByType<Rigidbody>(). Any means Unity may return any of the matches, with no promise about which, so use it when the scene has one of the kind. FindObjectsByType<T>(FindObjectsSortMode.None) returns all of them as an array. Like GameObject.Find, it goes through the whole scene and skips inactive objects, so call it once in Start().

Older tutorials write FindObjectOfType<T>(). That is the old name of this search: Unity 6 still compiles it, with a warning that it is obsolete.

challenge icon

Challenge

Medium

Build a day and night switch.

  • In Start(), find the scene's Light by its type and keep it in sun.
  • Each press of Space switches the light between night (intensity 0.2) and day (intensity 1). The game starts in daylight, at 1.

The switch must work in any scene, whatever the light is called, so do not look it up by name: the checks rename the light.

Press Play, click the game and press Space, then Check.

Try it yourself

using UnityEngine;

public class DayNight : MonoBehaviour
{
    private Light sun;

    void Start()
    {
        // Find the scene's Light by its type.
    }

    void Update()
    {
        // Space: switch between day (intensity 1) and night (0.2).
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics