The script for this game is very simple and basic in nature. Without a scoring mechanism or need for a state machine, the script is just a shell to house the reset function.
While the game is running, the script listens for the Touch Controller's B or Y buttons. If either of these are pushed, the script destroys the balls and bottles from the scene and replaces them with new prefabs. It is a very fast solution which is easy to follow:
- Open the BottleGameController script and edit it to match the following. The script starts by setting variables for the prefabs and the transforms:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BottleGameController : MonoBehaviour {
[SerializeField] GameObject BottlePyramidPrefab;
[SerializeField] GameObject FiveBallsPrefab;
private Vector3 PryamidPosition;
private Quaternion PryamidRotation;
private Vector3 BallsPosition;
private Quaternion BallsRotation;
In the Start() functions, we store the starting transforms for the bottle and ball prefabs. Storing these values will make it easier to position the new GameObjects after a reset:
// Use this for initialization
void Start () {
PryamidPosition =
GameObject.FindWithTag("bottles").transform.position;
PryamidRotation =
GameObject.FindWithTag("bottles").transform.rotation;
BallsPosition =
GameObject.FindWithTag("balls").transform.position;
BallsRotation =
GameObject.FindWithTag("balls").transform.rotation;
}
The Update() function, which is called during every frame in runtime, listens for the B and Y buttons to be pushed. When this happens, we destroy the current GameObjects and instantiate new versions, using the starting transforms of the original prefabs. Once the new objects are created, we set their tags so that they can be removed during the next reset activity:
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Button.Two") ||
Input.GetButtonDown("Button.Four")) {
Destroy (GameObject.FindWithTag("bottles"));
Destroy (GameObject.FindWithTag("balls"));
GameObject BottlePryamids = Instantiate
(BottlePyramidPrefab, PryamidPosition, PryamidRotation);
GameObject FiveBalls = Instantiate (FiveBallsPrefab,
BallsPosition, BallsRotation);
BottlePryamids.tag = "bottles";
FiveBalls.tag = "balls";
}
}
}
- Save the script and return to Unity.
- Select the BottleGame GameObject which houses the game's props. Notice the prefab fields in the Inspector panel.
- Drag the BottlePyramids and FiveBalls prefabs from the Prefab folder to the appropriate fields of the Bottle Game Controller component, as shown in Figure 8.8:
![](assets/5191fa70-2c39-404c-b9a4-f51f8ab42f10.png)
- Save the scene and project.
- Hit Play to test the scene.
- If all runs smoothly, activate all hidden objects.