Hello, Unity
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 1 of 85.
Everything in a Unity game is a GameObject: the ground, the player, the camera, even an invisible spawner. What a GameObject does comes from the components attached to it, and the components you write yourself are scripts.
A script is a C# class that extends MonoBehaviour. Unity runs the game and calls the script's methods for you. It calls Start() once, when the game begins, and Update() on every frame, many times a second. That is how a game moves: a tiny change in every frame.
void Start()
{
Debug.Log("The game has started");
}Debug.Log writes a message to the Console, the panel under the game. The script in this lesson is already finished: press Play and watch the cube come alive.
Challenge
EasyThis script is already finished: run it and see what it does.
- In
Start(),Debug.Log("Hello, Unity!");writes a message in the Console once. - In
Update(), two lines turn the cube and move it up and down on every frame.
Press Play: the cube spins and floats, and the Console shows Hello, Unity!. Then Check.
Try it yourself
using UnityEngine;
public class HelloUnity : MonoBehaviour
{
public float spinSpeed = 120f;
void Start()
{
Debug.Log("Hello, Unity!");
}
void Update()
{
transform.Rotate(0, spinSpeed * Time.deltaTime, 0);
float height = 1f + Mathf.Sin(Time.time * 2f) * 0.5f;
transform.position = new Vector3(0, height, 0);
}
}
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