【问题标题】:UnityScript to C# in UnityUnity 中的 UnityScript 到 C#
【发布时间】:2019-10-24 19:24:56
【问题描述】:

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

【问题讨论】:

  • 计时器和放映时间的浮点值应为 0.0f 和 3.0f。你有“ff”,这是无效的。此外,您没有为脚本中的所有方法定义一个类。如果这一切都包含在一个从单一行为派生的公共类中?除此之外,如果您可以提供尝试运行脚本时在控制台中看到的错误,那将证明是有用的。
  • 我试过 0.0f 和 3.0f。仍然没有任何改变。主要问题是我无法播放场景,因为它说“必须在进入播放模式之前修复所有编译器错误”。没有这个代码,我可以进入播放模式。
  • 您需要分享错误。它们将逐行显示在控制台中,突出显示代码中存在语法错误的行。
  • 花一些时间学习使用 Unity 的调试工具,并可能使用合适的 IDE 进行 C# 开发是个好主意。 Notepad++ 对于编译语言来说是一个很差的工具。
  • @Herohtar 它实际上是 UnityScript,它是 JS,也不是 JS。这就是为什么它有自己的标签,但与带有 Unity 引擎额外插件的 JavaScript 99% 相同。

标签: c# unity3d unityscript


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-04-26
    • 2013-10-05
    • 2012-11-26
    • 1970-01-01
    • 2017-06-09
    • 2015-05-16
    • 1970-01-01
    • 2015-03-15
    • 2012-11-12
    相关资源
    最近更新 更多