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
MediumBuild a day and night switch.
- In
Start(), find the scene'sLightby its type and keep it insun. - Each press of Space switches the light between night (
intensity0.2) and day (intensity1). 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).
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon