我在在运行时中将我编写的脚本添加到多维数据集时遇到了一些问题。我看到很多其他人问过这个问题,但他们似乎已经解决了。
代码:
// 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”的脚本,该脚本用最后一行代码完成。这不会出现任何错误,但是当游戏运行时未添加脚本。有人可以帮忙吗?我查看了文档,但它主要显示了我在做什么。
最佳答案
确保脚本中的脚本名称和类名称相同。除此之外,您的代码没有任何问题。甚至官方文档也是这样做的:
// Adds the sphere collider to the game object SphereCollider sc = gameObject.AddComponent<SphereCollider>();
和this answer在 Unity 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/