unity3d Unity中的UnityScript到C#

0yycz8jy  于 2022-11-16  发布在  C#
关注(0)|答案(1)|浏览(276)

我用UnityScript编写了这段代码。我需要用C#编写它。当我使用在线转换器时,似乎出现了编译器错误。问题是什么?
它将用于在UI文本中显示3秒钟的文本。我是Unity的新手,所以我可能没有解释好。
UnityScript程式码:

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();
}

C# Converter的输出似乎有一些问题:

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();
}
jchrr9hc

jchrr9hc1#

在C#脚本中,您必须从MonoBehaviour派生。下面的脚本将工作=)

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();
    }
}

相关问题