Unity添加组件(三角形)不工作

本文关键字:工作 三角形 添加 组件 Unity | 更新日期: 2023-09-27 17:54:41

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

Unity添加组件(三角形)不工作

将GameObject小写为GameObject。GameObject是一种类型,GameObject是对附加GameObject的引用。

你还添加了两次网格过滤器,这是一个错误。缓存您的组件,以便以后可以像这样使用它们:

编辑:认为你的"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};
    }
}

你应该将MeshFilter添加到gameObject而不是gameObject类中,而且你没有在任何地方使用MeshRenderer,所以为什么要添加它

    MeshFilter filter;
    MeshRenderer renderer;
    Mesh mesh;
 void Start(){
            gameObject.AddComponent<MeshFilter>();
            Mesh mesh = gameObject.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};
        }