UI Text not displaying public int but will display private int

I am trying to display the value of a public int that I can set in the inspector but it won’t show, if I use a private int instead it’s all fine. If I make a private int and set it equal to my public int that doesn’t work either. The really odd thing is that it DOES change the text in the inspector, just not the game view! What is going on?!

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

public class PortalController : MonoBehaviour {

    public Text scoreText;

    public int totalPortalPoints;
    private int portalPoints;

    void Start()
    {
        portalPoints = totalPortalPoints;
        Debug.Log("Portal points at: " + portalPoints.ToString());
        scoreText.text = "Portal points at: " + portalPoints.ToString();
    }

	void OnTriggerEnter(Collider other)
    {
        GameObject creep = other.gameObject;
        CreepController cc = (CreepController)creep.GetComponent("CreepController");
        portalPoints -= cc.portalPoints;
        Debug.Log(portalPoints); 
        Destroy(creep);
    }
}

Not really sure what you mean, sounds like you want UI Text to always show the value of totalPortalPoints. But it will only set the text once, because it happens at Start and no where else. What if you change Start to Update? void Update() { scoreText.text = "Portal points at: " + totalPortalPoints.ToString(); }

I will eventually want it to change at specified times but for now I want to get this working at the start

Even with your change it just says "Portal points at: " although in the inspector it has it with the number too

I copied the code you have in Start() in a new script, added an empty GameObject and attached the PortalController script. I also created a Text object and dropped it in the scoreText field in the Inspector. Everything worked just fine. Any value I put in the Inspector for totalPortalPoints (before clicking Play) was shown in the text field and in the console (after clicking Play). Funny thing...

I also added jessespike's Update() code, and every time I change the value of totalPortalPoints in the Inspector, the value of scoreText in Game View changed immediately. Apparently there is something wrong with your setup.

1 Answer

1

I fixed the issue by putting the code to update the text in it’s own method. I have no idea why this works, just glad it does.