Menu
CoddyTech

Find by Type

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 58 of 85.

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 that works whatever the light is called.

  1. In Start(), set sun = FindAnyObjectByType<Light>();.
  2. In Update(), on Space, set sun.intensity to 0.2f when it is above 0.5f, otherwise to 1f.

Press Play and press Space: night falls, and the next press brings day back. 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).
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground