📜  unity text display int - C# (1)

📅  最后修改于: 2023-12-03 15:20:52.471000             🧑  作者: Mango

Unity Text Display Int - C#

Unity Text Display Int refers to the process of displaying a numeric value (an integer) in a Unity game using the Text UI element. In C#, we can create a variable to store the value and then use it to update the Text UI element.

Creating a Text UI Element

To create a Text UI element, right-click on the Canvas (or a Panel within the canvas) in the hierarchy and select 'UI' and then 'Text'. This will add a Text UI element to the hierarchy.

We can then customize the look of the text by changing its font size, font color, position, etc.

Creating a C# Script

Next, we need to create a C# script that will update the Text UI element with the integer value.

using UnityEngine;
using UnityEngine.UI;

public class IntDisplay : MonoBehaviour {
    public int myInt;
    private Text myText;

    void Start() {
        myText = GetComponent<Text>();
    }

    void Update() {
        myText.text = "My integer is " + myInt.ToString();
    }
}
Explanation of Code

First, we import the necessary namespaces: UnityEngine and UnityEngine.UI. We then create a class called IntDisplay that inherits from the MonoBehaviour class.

We declare two member variables: myInt (of type int) and myText (of type Text). myInt will store the integer value, and myText will reference the Text UI element.

In the Start() method, we use the GetComponent() method to get a reference to the Text UI element and store it in the myText variable.

In the Update() method, we use the property of myText called text to set the text displayed by the Text UI element. We build a string using the integer value stored in myInt and the ToString() method to convert it to a string.

Assigning Values

To assign a value to myInt, we can do it in the Unity Editor by selecting the GameObject that has the IntDisplay script attached to it. In the inspector panel, we can modify the value of myInt.

Alternatively, we can assign a value to myInt in the script itself by modifying the Start() method.

void Start() {
    myInt = 10;
    myText = GetComponent<Text>();
}
Conclusion

In conclusion, Unity Text Display Int is a simple process that involves creating a Text UI element and writing a C# script that updates the element's text with the value of an integer. The C# script performs this update using the property of the Text UI element called text.