Recap: Nearest Coin
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 61 of 85.
This recap puts the chapter together: a search by tag at the moment it is needed, a loop over what it finds, and the distance to each one.
Challenge
MediumGive the player a coin radar: Space names the nearest coin.
- On Space, start with
GameObject nearest = null;andfloat best = Mathf.Infinity;. - For each coin in
GameObject.FindGameObjectsWithTag("Coin"), keep it when its distance to the player is belowbest. - Log
"Nearest coin: " + nearest.name.
Press Play, drive and press Space: the Console shows Nearest coin: Silver. Then Check.
Try it yourself
using UnityEngine;
public class CoinRadar : MonoBehaviour
{
[SerializeField] private float speed = 4f;
void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += new Vector3(0, 0, speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.position -= new Vector3(0, 0, speed * Time.deltaTime);
}
// Space: log the name of the nearest coin.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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