- Home /
My code will not change Canvas Text at all [No errors]
I set this code up and it doesn't change the Canvas Text at all an it has no errors according to unity.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HealthManager : MonoBehaviour {
Text Text;
private int Health=0;
// Use this for initialization
void Start () {
Text = gameObject.GetComponent<Text>();
}
// Update is called once per frame
void Update () {
Text.text="Health : " + Health;
}
}
Answer by DoTA_KAMIKADzE · May 06, 2015 at 08:19 PM
Bad idea to name your text variable with equal name to Text class...come up with a different name...like:
Text yourText;
Nevertheless it should work anyway, does an object which contain this script contain Text component as well? Have you set Font and width/height of it so that your text is big enough to be seen?
P.S. To be sure that your component is detected you can verify it like that:
Text yourText;
void Start()
{
yourText = GetComponent<Text>();
Debug.Log(yourText != null);
}
I have changed the code to:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Health$$anonymous$$anager : $$anonymous$$onoBehaviour {
Text Health;
private int Health_int=0;
// Use this for initialization
void Start () {
Health = gameObject.GetComponent<Text>();
Debug.Log(Health != null);
}
// Update is called once per frame
void Update () {
Health.text="Health : " + Health_int;
}
}
But I am just a begging to C# thing the Debug thing nothing happened and yes the text is big enough to see as I can see it but its not changing to what I set.
Thanks anyway
Debug.Log should display info in your Console view.
If it doesn't display anything there then your script is disabled, if it shows false then Text component is absent, if it shows true then everything should work if you can visually see text (e.g. when entered directly in Inspector).
Answer by Makarei · Oct 26, 2015 at 12:31 PM
The best way is to make sure your text object is called health, if you have a maxhealth its will work better.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HealthManager : MonoBehaviour
{
Text health;
Player player;
// Use this for initialization
void Start ()
{
health = gameObject.GetComponent<Text>();
player = Player.player;
//Debug.Log(Health != null);
}
// Update is called once per frame
void Update ()
{
health.text = player.health + " / " + player.maxHealth;
}
}
No, once per frame (and for example 60fps = 60x Update() per second)
Answer by ProCreeper_2000 · Sep 04, 2016 at 12:35 PM
Should work, did for me!
using UnityEngine; using UnityEngine.UI; using System.Collections; public class HealthManager : MonoBehaviour { Text myText; private int Health = 100; // Use this for initialization void Start () { myText = myText.GetComponent<Text>(); } // Update is called once per frame void Update () { myText.text = "Health : " + Health; } }