Recap: Nearest Coin
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 47 of 67.
Challenge
MediumGive the player a coin radar. The arrows already move the player. Add this: each press of Space logs the name of the nearest object tagged Coin, as Nearest coin: Silver.
- The coins have different names, and the rock is not a coin.
- Coins disappear when they are picked up (they are hidden with
SetActive(false)), so search for the coins at each press, not once inStart().
Press Play, drive around and press Space, 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.
}
}
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