以下代码应该为三角形添加一个3d对象,但我收到错误
Assets / Scripts / 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};
}
}
答案 0 :(得分:3)
将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};
}
}
答案 1 :(得分:0)
你应该将MeshFilter添加到gameObject而不是GameObject类,你也没有在任何地方使用MeshRenderer,所以为什么要添加它
import java.util.*;
import java.io.*;
class Example {
public static void main(String[] args) throws IOException {
final int count = 1000;
ArrayList<Boolean> list = new ArrayList<>(count);
list.addAll(Collections.nCopies(count, Boolean.TRUE));
System.out.printf("ArrayList: %d%n", sizeOf(list));
boolean[] array = new boolean[count];
Arrays.fill(array, true);
System.out.printf("boolean[]: %d%n", sizeOf(array));
BitSet bits = new BitSet(count);
bits.set(0, count);
System.out.printf("BitSet: %d%n", sizeOf(bits));
}
static int sizeOf(Serializable obj) throws IOException {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ObjectOutputStream objsOut = new ObjectOutputStream(bytesOut);
objsOut.writeObject(obj);
return bytesOut.toByteArray().length;
}
}