c# - Unity 添加组件

标签 c# unity3d

我在在运行时中将我编写的脚本添加到多维数据集时遇到了一些问题。我看到很多其他人问过这个问题,但他们似乎已经解决了。

代码:

            // Insert
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            // Appearance
            cube.GetComponent<Renderer>().material.SetColor("_Color", Color.yellow);
            Shader transparent;
            transparent = Shader.Find("UI/Default");
            cube.GetComponent<Renderer>().material.shader = transparent;
            //
            //
            // Postioning
            //cxcxcxcxc
            cube.transform.position = new Vector3((xpos), (ypos), zpos);
            cube.transform.localEulerAngles = new Vector3(90, 0, 0);


            var myScript = cube.gameObject.AddComponent<CoinCollect>();

此代码创建一个立方体,添加着色器并对其进行定位。我现在想向其中添加一个我创建的名为“CoinCollect”的脚本,该脚本用最后一行代码完成。这不会出现任何错误,但是当游戏运行时未添加脚本。有人可以帮忙吗?我查看了文档,但它主要显示了我在做什么。

最佳答案

确保脚本中的脚本名称和类名称相同。除此之外,您的代码没有任何问题。甚至官方文档也是这样做的:

Unity Docs:

// Adds the sphere collider to the game object  
SphereCollider sc = gameObject.AddComponent<SphereCollider>();

this answerUnity Answers 上建议用同样的方式添加脚本:

AddComponent and GetComponent use the name of the class in the script, not a path to the script.

AddComponent("DestroyOnTouch");

Or preferably:

 AddComponent<DestroyOnTouch>();

As this will give you a compile time error if the class cannot be found, rather than a runtime error.

还有:

  • 你怎么知道脚本不起作用?尝试一个简单的 Debug.Log() 并验证,它可能是脚本本身的一些错误。
  • 您在问题中发布的代码是否执行过?你把它放在哪里了?在脚本中?然后检查它是否附加到某个 gameObject 或被调用。此外,您还可以考虑检查是否调用了编写代码的方法。
  • 要检查以上内容,请将 Debug.Log("The main script ran"); 放在同一代码块中并运行您的游戏。然后,检查 Unity 中的控制台。

关于c# - Unity 添加组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516628/

相关文章:

unity3d - 球在全息镜头中穿过地面,但在统一时效果很好。空间映射

ios - 应用程序经过广泛测试,也得到了苹果的认可,但一旦进入 App Store,所有用户都会崩溃

android - 在 Unity 中使用 Play Asset 交付后应用程序大小翻倍

c# - 仅限二进制数 TextBox

c# - 将 trie 保存到磁盘

unity3d - 编辑器窗口截图

c# - 如何调用具有 bool 值 true unity C# 的数组元素

c# - 如何在 C# 中访问不强制转换的多态方法

C# UDPClient 不良吞吐量

c# - 如何防止函数中的隐式转换?