将 UnityScript 翻译成 C#:yield & transform.position

Translation UnityScript to C# : yield & transform.position

我实际上正在努力将一个最初使用 UnityScript 的统一项目转换为 C#。我已经翻译了项目的大部分内容,但我遇到了一些问题:

第一个问题与yield有关:

yield Attack();
yield;

我已经替换了所有的 : yield WaitForSeconds() 但我不知道如何替换它。

其次 transform.position 的另一个问题:

transform.eulerAngles.y += Input.GetAxis("Horizontal") * speedIdleRotate;
transform.position.y = currentHeight;

抛出错误:

UnityEngine.Transform.eulerAngles is not a variable
UnityEngine.Transform.position is not a variable

似乎没有考虑 .y,但在 js 中我工作正常。如何在 C# 中处理?

在 JS 中,

yield; // this means that wait for one frame

在 C# 中,

yield return null;

我不是 100% 确定,但对于 yield Attack();

应该是

yield return Attack();

对于,

transform.eulerAngles.y += Input.GetAxis("Horizontal") * speedIdleRotate;

试试这个:

transform.eulerAngles = new Vector3( transform.eulerAngles.x , transform.eulerAngles.y + Input.GetAxis("Horizontal") * speedIdleRotate , transform.eulerAngles.z);

对于,

transform.position.y = currentHeight;

试试这个:

transform.position =new Vector3(transform.position.x,currentHeight,transform.position.z);

抱歉,如果我有什么不对的地方。

我只想复制 Cyclops answer 的 yield 语句。

Unity C# 中的产量与 Unity Javascript

虽然 Unity 的文档确实(简要地)涵盖了在编写 C# 脚本时使用 Yield 的语法差异(第 4 步),但还有一个涵盖 How do I Use Yield in C# 的 Unity Answer,其中有更详细的解释。此外,equalsequals 的答案有一个 link 值得一试的协程教程。

Unity 的 Yield 比 .NET C# Yield 具有更多功能

以上段落涵盖了 Unity 的 C# 与 Javascript 语法的差异。但是,我认为值得解释的是,Unity 的 Yield 语句(在 C# 和 Javascript 中)的行为具有一些在 Microsoft 的 .Net C# 行为中没有的附加功能。

基本上,Unity 在 Yield 中添加了 YieldInstruction(和子 类,例如 WaitForSeconds)。这些 类 使 Yield 能够暂时暂停函数,直到满足条件。如果它的参数为零,它会暂停一帧。如果它有一个参数 WaitForSeconds:

yield return new WaitForSeconds (2.0f); // pauses for 2 seconds.

然后它会暂停几秒钟。如果参数是另一个协程,则它会暂停,直到该协程完成。

**

Yield only works this way inside a Coroutine. To start a Coroutine in C#, you use StartCoroutine, whereas it is automatically called in Javascript.

**

第二题回答 您需要记住上面给出的 link 描述的根本区别。很快我可以说:

这是因为您使用 C# 进行编码。在 javascript 中,编译器允许您修改 transform.position 的组件值,但在 C# 中不允许 - 您必须制作一个全新的 Vector3 并在一次操作中分配它。

在 Javascript 中,编译器基本上 'hides' 它在幕后为您做这件事。more