user4530102
user4530102

Reputation:

unity add component (triangle) not working

The following code is supposed to add a 3d Object for Triangle but I am recieving error

Assets/Scripts/MakeTriangle.cs(6,28): error CS0120: An object reference is required to access non-static member `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};
    }
}

Upvotes: 2

Views: 1662

Answers (2)

Milad Qasemi
Milad Qasemi

Reputation: 3049

you should add the MeshFilter to the gameObject not GameObject class and also you didnt used MeshRenderer anywhere so why did you added it

    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};
        }

Upvotes: 0

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

Lowercase your GameObject to gameObject. GameObject is a type, gameObject is a reference to the attached GameObject.

Also you are adding the MeshFilter twice, that is a mistake. Cache your components so you can use them later like this:

EDIT: thought your "GetComponent" was another "AddComponent". So i retract my last statement saying it was a mistake.

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};
    }
}

Upvotes: 3

Related Questions