We've written one controller for the app, PictureController, which manages a picture. We could add a CreateNewPicture function there, but what if the scene is empty and there is no PictureController? What component function gets called to add a new picture to the scene? Let's create a separate GameController to support creating new pictures.
There should only be one GameController in our scene, so we make it a singleton. The singleton pattern ensures there will never be more than one instance of a class. In Unity and C#, we can implement singletons. In your Scripts folder, create a new C# script and name it GameController:
File: GameController
using UnityEngine; public class GameController : MonoBehaviour { public static GameController instance; void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); } } }
Now we'll add a CreateNewPicture function to GameController to spawn a new instance of the default picture. We'll place the new picture in front of the user's current gaze, a fixed distance away. Add the following code to the class:
public GameObject defaultPictureObject; public float spawnDistance = 2.0f; public void CreateNewPicture() { Vector3 headPosition = Camera.main.transform.position; Vector3 gazeDirection = Camera.main.transform.forward; Vector3 position = headPosition + gazeDirection * spawnDistance; Quaternion orientation = Camera.main.transform.localRotation; orientation.x = 0; orientation.z = 0; GameObject newPicture = Instantiate(defaultPictureObject, position, orientation); newPicture.tag = "Picture"; }
The GameController references the DefaultPicture prefab to spawn, instantiates it, and tags it as a Picture so we can find them later. Let's now add it to the scene:
- In Hierarchy, click Create Empty game object at the root of the scene, named GameController.
- Add the GameController component script to it.
- Drag the DefaultPicture from the Hierarchy into your Project AssetsApp/Prefabs/ folder.
- Drag the DefaultPicture prefab from the Assets folder onto the Default Picture Object slot.
Next, we support Add and Delete in the PictureController.