Creating an Instructions Controller

We're now going to create a controller object and script for our project. This first implementation will be relatively simplistic. It will grow and improve later in the chapter. In Unity, perform the following:

  1. In the Project window, create a C# Script in your scripts folder (Assets/HowToChangeATire/Scripts/) and name it InstructionsController.
  2. In Hierarchy, select Create Empty object.
  3. Rename it Game Controller.
  4. Drag the InstructionsController script into Inspector, adding it as a component.

Save the scene and then open the script for editing. Like most Unity scripts, this class will be derived from MonoBehaviour. We write a couple of functions required to update the UI based on user input. Open InstructionsController.cs for editing and write the following:

File: InstructionsController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InstructionsController : MonoBehaviour {
public Text stepText;

private int currentStep;

void Start () {
currentStep = 0;
CurrentInstructionUpdate();
}

public void NextStep() {
currentStep++;
CurrentInstructionUpdate();
}

public void PreviousStep() {
currentStep--;
CurrentInstructionUpdate();
}

private void CurrentInstructionUpdate() {
stepText.text = "Step: " + currentStep;
}
}

Note, at the top of the file, we add using UnityEngine.UI; so the Unity UI components will be recognized, including the Text reference.

The script is going to update the title text with the current step number. It knows which text element to change because we declare a public Text stepText. Later, we'll populate that in the Inspector.

In this script, we keep track of the currentStep, which is an integer that is initialized to 0 in Start(), incremented by one in NextStep(), and decremented by one in PreviousStep(). Any time the step number changes, we call CurrentInstructionUpdate() to update the text on the screen.

Save the script file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.156.140