以下代码应该为Triangle添加一个3d对象,但是我收到错误消息
资产/脚本/MakeTriangle.cs(6,28):错误CS0120:访问非静态成员`UnityEngine.GameObject.AddComponent(System.Type)'时需要对象引用
using UnityEngine;
using System.Collections;
public class MakeTriangle : MonoBehaviour {
void Start(){
GameObject.AddComponent<MeshFilter>();
GameObject.AddComponent<MeshRenderer>();
Mesh mesh = GetComponent<MeshFilter> ().mesh;
mesh.Clear();
mesh.vertices = new Vector3[] {new Vector3(0,0,0), new Vector3(0,1,0), new Vector3(1,1,0)};
mesh.uv = new Vector2[] {new Vector2(0,0), new Vector2(0,1), new Vector2(1,1)};
mesh.triangles = new int[] {0,1,2};
}
}
最佳答案
将您的GameObject小写为gameObject。 GameObject是一种类型,gameObject是对附加GameObject的引用。
另外,您还要两次添加MeshFilter,这是一个错误。缓存组件,以便以后可以像这样使用它们:
编辑:以为您的“ GetComponent”是另一个“ AddComponent”。因此,我撤回了最后的声明,说这是一个错误。
using UnityEngine;
using System.Collections;
public class MakeTriangle : MonoBehaviour {
MeshFilter filter;
MeshRenderer renderer;
Mesh mesh;
void Start(){
filter = gameObject.AddComponent<MeshFilter>();
renderer = gameObject.AddComponent<MeshRenderer>();
mesh = filter.mesh;
mesh.Clear();
mesh.vertices = new Vector3[] {new Vector3(0,0,0), new Vector3(0,1,0), new Vector3(1,1,0)};
mesh.uv = new Vector2[] {new Vector2(0,0), new Vector2(0,1), new Vector2(1,1)};
mesh.triangles = new int[] {0,1,2};
}
}
关于c# - 统一添加组件(三角形)不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30746649/