First Script

Script structure

In Unity, a script is used to control the behavior of GameObjects and define game logic. Scripts are written in C# and allow developers to create interactions, manage physics, handle inputs or control animations.

../_images/structure.png

The line: using UnityEngine; imports the internal Unity libraries and their classes.

A script typically extends the MonoBehaviour class through inheritance. Thus we can override built-in Unity methods like:

  • Start(): Runs once when the object is initialized

  • Update(): Runs every frame, useful for real-time updates

First Script

Scene setup

  • Navigate to AssetsScenesIntro

  • Create a new scene called « FirstScript »

  • Double click to open it

  • Create a plane for the ground and apply a green material

  • Create a cube, apply a blue material and and move it upwards

../_images/scene1.png

Create a script

  • In the Assetsintro folder, right click to open the context menu

    ../_images/rclick.png
    • Select Create > Scripting > MonoBehaviour Script

    • Rename it « Bonus »

    ../_images/bonus.png

Avertissement

At this point the script and the cube are not associated

Association

  • To associate a script with an object, drag and drop the script icon onto:

    • The object in the Scene view

    • Or the object in the Hierarchy

    ../_images/assoc.gif
  • Select the cube and check that the script is now part of the gameobject:

    ../_images/ins.png

Open a script

  • In the Assets window, double click on the script icon

    • The script opens in Visual Studio

  • Copy paste the following code:

using UnityEngine;

public class BonusScript : MonoBehaviour
{
        void Start()      { }

        void Update()
        {
                transform.Rotate(0, 0.1f, 0);
        }
}
  • The Rotate function makes the object rotate around the vertical axis

  • Press CTRL-S to save the script

    • Notice that this triggers the recompilation of the script in the Unity

Run

  • In the scene view, make sure the cube is properly centered in the view

  • In the Hierarchy window, right click on the camera

    • Select Align With View to obtain the same view during Play mode

  • Press the Play button

    • The cube rotates automatically

    ../_images/rot.gif

External variables

You can add variables to your script to parameterize its behavior. Moreover, you can « export » these variables into the Inspector to edit them directly without opening the source code.

Rotation speed

Unity uses degrees for rotation, so each time the Update() function is called, the cube rotates by 1 degree. However, we don’t know how many times per second this function is executed. Additionally, the execution rate constantly varies depending on the current cpu load.

To precisely control the rotation speed, we must use physics” law. Here, we recall the formula that gives the rotation angle based on the rotation speed and the time interval:

\[angle = dT \times Rot_{speed}\]

Unity provides the variable Time.deltaTime which corresponds to dT.

  • In Visual Studio, create a public float variable RotSpeed

  • In the Update() function, apply the given formula

  • Select the cube and scale it to obtain a tube shape

  • In the Inspector, look at the script section

    • The variable rotSpeed is now present

    • Set its value to 180 which corresponds to 1/2 turn per second

    ../_images/rotspeed.png
  • Enter Play mode

    ../_images/180.gif
    • The bar makes one full turn every 2 seconds

  • Change the rotation speed value to 360

    ../_images/360.gif
    • The bar makes one full turn every second

Avertissement

You can interactively modify any values in the Inspector during Play mode. This is very useful for testing and debugging. However, keep in mind that any changes made in Play mode will be lost once you exit. Only values set in Edit mode are permanently retained.

Blinking light

  • Exit Play mode

  • Add two external variables: public Material

    • In the Assets folder, go to AssetsSolidColorMaterials

    • In the Inspector, drag and drop two colors to initialize the two materials

      ../_images/2mats.png ../_images/blink.gif
  • To retrieve the elapsed time since the start of the game, use the Time.time float variable

  • Every second, change the cube’s material:

    • Renderer r = GetComponent<Renderer>();

    • r.material = …