Scripting the mole game controller

Now we will focus on building a controller script for the mole game. This script will manage the Score Board text elements and the starting times for the moles:

  1. Begin the process by creating a new script on the MoleGame GameObject. Name the script MoleGameController.
  2. Double-click the new script to open it in your editor.
  1. Modify the script to match the following functions and methods:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MoleGameController : MonoBehaviour {

[SerializeField] Text timerUI, scoreUI;
[SerializeField] float startingTimeInSeconds = 30f;

List<MoleController> moles;
int score = 0;
float timer = 0f;
bool isTiming;

void Start() {
moles = new List<MoleController>();
StartGame();
}

void Update() {
int scoreAccumulator = 0;
foreach (MoleController mole in
GetComponentsInChildren<MoleController>()) {
}

score = scoreAccumulator;
scoreUI.text = score.ToString();

int minutesLeft = (int) Mathf.Clamp((startingTimeInSeconds -
timer) / 60, 0, 99);
int secondsLeft = (int) Mathf.Clamp((startingTimeInSeconds -
timer) % 60, 0, 99);
timerUI.text = string.Format("{0:D2}:{1:D2}", minutesLeft,
secondsLeft);
}

void FixedUpdate() {
if (isTiming) {
timer += Time.deltaTime;
}
}

public void StartGame() {
foreach (MoleController mole in
GetComponentsInChildren<MoleController>()) {
moles.Add(mole);
mole.StartGame();
}
StartTimer();
}

public void StopGame() {
StopTimer();
}

// Starts Timer
public void StartTimer() {
timer = 0f;
isTiming = true;
}

public void StopTimer() {
isTiming = false;
}
}

Selecting the MoleGameObject will reveal three public fields: Timer UI, Score UI, and Starting Time. Starting Time already has a default value, but the other two will need to be set before running the game.

  1. Click the selection target for Timer UI and Score UI and set their values to the appropriate UI Text object.
..................Content has been hidden....................

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