GameController

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:

  1. In Hierarchy, click Create Empty game object at the root of the scene, named GameController.
  2. Add the GameController component script to it.
  3. Drag the DefaultPicture from the Hierarchy into your Project AssetsApp/Prefabs/ folder.
  4. Drag the DefaultPicture prefab from the Assets folder onto the Default Picture Object slot.

Next, we support Add and Delete in the PictureController.

Reminder: Now that the DefaultPicture is a prefab, if you make changes to it or any of its child objects in Hierarchy, you must remember to press Prefab Apply to save those changes to the prefab version.
..................Content has been hidden....................

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