【问题标题】:How to convert this code from Unityscript to C#?如何将此代码从 Unityscript 转换为 C#?
【发布时间】:2014-08-20 01:21:19
【问题描述】:

我正在尝试将 Unity UnityScript 转换为 C#。我收到此错误:

资产/脚本/BoostPlatformCheck.cs(40,36):错误 CS0019:操作员 ==' cannot be applied to operands of typeint' 和 `object'

这里是 C# 代码:

int collidedWith = collisionInfo.gameObject.GHetInstanceID();  
ArrayList collided = new ArrayList();

....

     if(collidedWith == collided[collided.Count - i - 1])
            {
                alreadyExists = true;
                return; 
            }

当我将它从 JS 转换为 C# 时,我将 Array 更改为 ArrayList,并将 collided.length 更改为 collided.Count。

【问题讨论】:

  • 试试: if(collidedWith ==Convert.ToInt32(collided[collided.Count - i - 1]))
  • 您的ArrayList 中存储了什么?如果它们都是一样的——看起来它们是一样的; ints - 那么您应该使用 List<int>.. 这将允许您进行比较。另外,不要按照蒂姆在此评论上方所说的去做
  • 我很震惊蒂姆的评论有一个赞成票——它是 2014 年的人——我们为此提供了强类型容器。您不应该从 .NET 2 及更高版本的 ArrayList 转换对象。在这个简单的例子中肯定不会。
  • 它也是 UnityScript,而不是 JavaScript

标签: c# unity3d unityscript code-conversion


【解决方案1】:

我将 Array 更改为 ArrayList 并将 collided.length 更改为 collided.Count 当我将它从 JS 转换为 C# 时

由于您只想将代码转换为 C#,因此请使用 int 数组而不是 ArrayList:

int[] collided = new int [10]; // This is how you declare arrays in C#

然后你可以像在 Javascript 中一样使用collided.length 来查找数组的长度。

还有一件事,C# 中的数组有一个内置函数 Contains(),它可能会在您的情况下为您提供帮助,这看起来就像您正在遍历数组以比较 collidedWith。为简化起见,您可以删除循环并尝试以下操作:

// This means collidedWith exists within collided, so you won't need the loop anymore
if(collided.Contains(collidedWith)) 
    alreadyExists = true;

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多