I have written some code for generating a triangle -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeshGenerator : MonoBehaviour
{
private Mesh mesh;
private int[] triangles;
private Vector3[] vertices;
void CreateTriangle()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
triangles = new int[]
{
0,
1,
2
};
vertices = new Vector3[]
{
new Vector3(0, 0, 1),
new Vector3(0, 1, 0),
new Vector3(1, 0, 0)
};
mesh.Clear();
mesh.triangles = triangles;
mesh.vertices = vertices;
}
void Start()
{
CreateTriangle();
}
}
But for some reason this doesn’t seem to work. It gives me the error -
Failed setting triangles. Some indices are referencing out of bounds vertices. IndexCount: 3, VertexCount: 0
UnityEngine.Mesh:set_triangles (int[ ])
MeshGenerator:CreateTriangle () (at Assets/MeshGenerator.cs:27)
MeshGenerator:Start () (at Assets/MeshGenerator.cs:32)
Any help regarding what’s wrong would be appreciated. Thanks in advance!
But take note that you’re setting mesh.triangles before you’re setting mesh.vertices. At the time you set the triangles array, what is in the vertices array which it is referring to?
(In Unity some things which look like they’re just assigning variables actually call methods on the native side of the engine.)
Thank you guys so much! It worked! I can finally start my work on mesh generation! I’m happy to know this fundamental thing now that I’ve been missing.