UI in VR: Using the Worldspace Canvas

Rushil Reddy

We are going to keep track of score every time a zombie is killed and display it in our world. Right click in the hierarchy tab and click UI>Canvas. Change its render mode from screen space- overlay to worldspace. Now edit its scale transform to (.1, .1, .1).

Add Component>Text and change it to say “Score:” Change its transform values to match ours.

Now Add Component> Script and call it scoreManager. Add the following code to help manage our score. Make sure you don’t forget to add the line using UnityEngine.UI or the script won’t compile.

public class scoreManager : MonoBehaviour {

 

   public static scoreManager instance;

   public int score;

 

   private Text text;                      // Reference to the Text component.



   void Start()

   {

       instance = this;

       // Set up the reference.

       text = GetComponent<Text>();

 

       // Reset the score.

       score = 0;

   }



   void Update()

   {

       // Set the displayed text to be the word "Score" followed by the score value.

       text.text = "Score: " + score;

   }

 

   public void Increase(int num)

   {

       score += num;

   }

}

 

Now open up the zombieController and add this line whenever a zombie dies. ScoreManager.instance.Increase(10);

Hit Play and our score counter should update whenever a zombie is downed!