I have this code written in UnityScript. I need to write it in C#. When I use an online converter there seems to be a compiler error. What is the problem?
It is going to be used to display a text for 3 seconds in UI Text. I am new to Unity, so I might not have explained well.
UnityScript code:
private var timer: float;
private var showTime: float;
private var activeTimer: boolean;
private var message: String;
private var uiText: UI.Text;
function startTimer()
{
timer = 0.0f;
showTime = 3.0f;
uiText.text = message;
activeTimer = true;
}
function Start()
{
uiText = GetComponent(UI.Text);
}
function Update()
{
if (activeTimer)
{
timer += Time.deltaTime;
if (timer > showTime)
{
activeTimer = false;
uiText.text = "";
}
}
}
function showText(m: String)
{
message = m;
startTimer();
}
The output from C# Converter that seems to have some problem:
private float timer;
private float showTime;
private bool activeTimer;
private string message;
private UI.Text uiText;
void startTimer()
{
timer = 0.0ff;
showTime = 3.0ff;
uiText.text = message;
activeTimer = true;
}
void Start()
{
uiText = GetComponent<UI.Text>();
}
void Update()
{
if (activeTimer)
{
timer += Time.deltaTime;
if (timer > showTime)
{
activeTimer = false;
uiText.text = "";
}
}
}
void showText(string m)
{
message = m;
startTimer();
}
In a C# script you have to derive from MonoBehaviour. The script below will work =)
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Display a text for 3 seconds in UI Text.
/// </summary>
class DisplayText : MonoBehaviour
{
private float timer;
private float showTime;
private bool activeTimer;
private string message;
private Text uiText;
void Start()
{
uiText = GetComponent<Text>();
}
void Update()
{
if (activeTimer)
{
timer += Time.deltaTime;
if (timer > showTime)
{
activeTimer = false;
uiText.text = "";
}
}
}
void startTimer()
{
timer = 0.0f;
showTime = 3.0f;
uiText.text = message;
activeTimer = true;
}
void showText(string m)
{
message = m;
startTimer();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.