gpt4 book ai didi

c# - 统一添加组件(三角形)不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:23 26 4
gpt4 key购买 nike

下面的代码应该为三角形添加一个 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};
}
}

最佳答案

将您的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com