Two questions about text elements?

First, I am using a modified version of this in my own game. I have a text element and I want it to go up by 1 every time you shoot a target. In the code attached to each target I have the following. Instead of increasing the value by 1, it keeps adding 1's to the end. So after shooting 5 targets it will display "11111". How do I change this to increment 1 at a time like an int?


using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.UI; 

public class Destroy : MonoBehaviour { 
public Text points; 




void  OnTriggerEnter(Collider col) 
{ 
if (col.CompareTag("bullet")){ 
Debug.Log(points.text); 
points.text += 1; 
Debug.Log(points.text); 
Destroy(gameObject); 
} 
} 
} 

Second, t he text appears on screen perfectly on my pc but when I go into VR to play the game, the text no longer shows up. Do you know why this is?

  • Jonathan Gonzalez(jgonzalez) replied

    Text elements will only display a string value.  So when you have points.text += 1; It thinks you're trying to build a word or a sentence since it treats the 1 as a character and not a number. You need a separate int or float variable to keep track of points, you then use that for your points text as such:

    public int playerScore;
    public Text pointsText;
    pointsText.text = playerScore.ToString();
    

    Since playerScore is an integer it needs to be "converted" to a string and you do that by using "ToString()" after it. You could also combine it with an actual string and it won't be necessary like this:

    pointsText.text = "Player Score " + playerScore;
    

    Also just to be clear, you would increment the playerScore, the text would only display what that value is. So you'd probably update the playerScore and pointsText at the same time as such:

    void UpdateScore ()
    {
    playerScore ++;
    pointsText.text = playerScore.ToString();
    }
    

    This would be called anytime you wanted to update the player's score which would then also update what the text should say. Using "playerScore++" updates the value by 1, you could also replace it with a higher value if you'd prefer. 

    The UI by default uses Screen Space, which means it'll display as an overlay for your device. This works fine for most traditional hardware such as a PC or consoles, but VR works off a two camera system so it can't be used in that way. Creating a HUD for VR means the UI elements will be in world space. These would essentially float in front of the player, or could be attached to other objects.  To change a canvas to world space you need to select it and on the "Canvas" component change the render mode to World Space as such:

    You can then resize the entire canvas just like you would any other game object and place it in front of your camera. You could also make it a child of the "eye" camera so that it's always moving with the head.