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
MediumBuild a day and night switch that works whatever the light is called.
- In
Start(), setsun = FindAnyObjectByType<Light>();. - In
Update(), on Space, setsun.intensityto0.2fwhen it is above0.5f, otherwise to1f.
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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground