【问题标题】:Why does this script get a parsing error?为什么这个脚本会出现解析错误?
【发布时间】:2012-11-25 00:07:19
【问题描述】:

我现在不太了解 C#;我只是以光速通过 Unity 速成课程。

我尝试将此脚本从我的桌面拖放到 Unity 项目视图中的资产文件夹,但它显示“解析错误 1,13”。我不确定脚本有什么问题。有经验的人可以看一下吗?

var emitter : ParticleEmitter = GetComponentsInChildren(Partic­­leEmitter);

if (Input.GetButton("Fire1")){ emitter.emit=true;

}

else{

emitter.emit=false;

}

【问题讨论】:

  • 第一行第二次出现ParticleEmittercl之间似乎有一个特殊字符。

标签: c# unity3d


【解决方案1】:

我自己没有使用过带有 C# 的 Unity,但我可以告诉你,你的脚本甚至不是有效的 C# 语法。 C# 变量以以下两种方式之一输入:

  • 隐式:var x = SomeExpression; 其中 x 自动采用表达式的类型
  • 明确表示:ParticleEmitter x = SomeExpression;,其中 x 是 ParticleEmitter,并且表达式必须属于同一类型。

具体来说,该错误与您第一行中的: 有关。这是非法的 C# 语法,因为唯一可以合法出现在该位置的字符是 =

【讨论】:

  • 我是个白痴。它是 JAVASCRIPT。我没想到。当我读到你的第一句话时,我立刻意识到了这一点。那是两种可行的 Unity 语言,而且这个脚本是在线的,没有语言标签,我只是盲目地假设。真蠢。谢谢。
【解决方案2】:

这不是 C#,这是用 UnityScript(基于 JavaScript)编写的。

您可以这么说,因为“:”冒号字符在 UnityScript 中用作类型声明,但在 C# 中无效。

【讨论】:

    【解决方案3】:

    我自己从未使用过 C#,但我会尝试隐式类型声明,方法是在第一行省略“:ParticleEmitter”部分...

    【讨论】:

      【解决方案4】:

      GetComponentsInChildren() 返回组件的类型。解析错误可能来自编译器试图协调将Component 类型传递给ParticleEmitter 类型。

      来自 Component.GetComponentsInChildren 的 Unity3D 文档中的这个示例应该可以帮助您:

       // Disable the spring on all HingeJoints 
       // in this game object and all its child game objects
       var hingeJoints : Component[];
       hingeJoints = GetComponentsInChildren (HingeJoint);
       for (var joint : HingeJoint in hingeJoints) {
           joint.useSpring = false;
       }
      

      【讨论】:

        【解决方案5】:

        正如 CC Inc 所说,您提供的代码不是 C#

        我已尝试为您转换它:

        ParticleEmitter emitter = GetComponentsInChildren<ParticleEmitter>().FirstOrDefault();
        
        if (emitter != null)
        {
            if (Input.GetButton("Fire1"))
            {
                emitter.emit = true;
            }
            else
            {
                emitter.emit = false;
            }
        }
        

        GetComponentsInChildren 返回一个数组。因此,为了模仿你上面的内容,我已经说过我想要第一个,如果你找不到任何给我默认值(它是 null)。

        这可能不是您需要的,您可能只需要以下几行:

        bool fire = Input.GetButton("Fire1");
        ParticleEmitter[] emitters = GetComponentsInChildren<ParticleEmitter>();
        foreach(ParticleEmitter emitter in emitters)
        {
            emitter.emit = fire; 
        }
        

        上面将存储 Input.GetButton 的布尔结果,然后遍历它找到的所有发射器并将它们设置为与 Input.Getbutton 相同的值。

        显然以上只是猜测您想要什么,希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-04
          • 2020-02-03
          • 1970-01-01
          • 1970-01-01
          • 2013-12-30
          • 1970-01-01
          相关资源
          最近更新 更多