Float to String C#

This is a relatively simple question. I created a UI that is supposed to show the health of the player. However, because the health of the player is a float value, I cannot use it to update the text of the UI, which is a string. Any suggestions on how to make this work? Thanks.

float myFloat = 10f;

string myString = myFloat.ToString();

Tried that already, no luck.

public float totalHealth;
public string displayHealth = totalHealth.ToString();

Error: A field initializer cannot reference the nonstatic field, method, or property `lives.totalHealth’

What about this?

string myString = String.Parse(totalHealth);

In that example, totalHealth has no value.

You can also use something like:

public string displayHealth = string.Format("{0}", totalHealth);

Odd, it gives me the same error.

Do you mean I should do this which gives me an error saying: The name `String’ does not exist in the current context
public string displayHealth = String.Parse(totalHealth);
or this, giving me the same error?
public string displayHealth = displayHealth.Parse(totalHealth);

I think I am thinking of the wrong thing… sorry…

It’s fine, thanks anyway,

I may not be giving enough information. Here’s the whole script:

using UnityEngine;
using System.Collections;

public class lives : MonoBehaviour {
    public float totalHealth;
    public float damage;
    public float minimumHealth;
    public string displayHealth = totalHealth.ToString();
    public GUIText health = displayHealth;

    void Start () {

    }

    void Update () {

    }

    void OnCollisionEnter2D (Collision2D collision)
    {
        if (collision.gameObject.tag == "Death Trap")
        {
            totalHealth -= damage;
            health.text = totalHealth;
        }
        if (totalHealth <= minimumHealth)
        {
            Application.LoadLevel(Application.loadedLevel);
        }
    }
}

try setting a default to totalHealth.

public float totalHealth = 0f;

The error is because you are trying to call a method in your initialisation. Move the ToString call inside a method. Probably Update for UI stuff.

1 Like

Aha, I think you’re on to something. I pinpointed the problem which has something to do with the GUIText health variable. I tried removing it, and the error goes away. Also, when I do what you suggested, I get new errors, both saying that I ‘Cannot implicitly convert type string' to UnityEngine.GUIText’', pointing to line 24.

1 Like

On line 24: health.text = “”+totalHealth;

1 Like

You probably want to ditch GUIText for the new UI system.

But to solve your immediate problem you should be assigning the string to health.text instead of health.

Horray, no more errors! Thanks for the help. Now I just have to figure out how to connect the variable with the text itself…

Saved my life!Even after 5 years!

  • public static float totalHealth ;
  • public string displayHealth = totalHealth . ToString ();