The question is answered, right answer was accepted
Mesh not rendering correctly
My randomly generated mesh is not rendering for some reason Below is the script and a picture of the problem
[2]:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class MeshGenerator : MonoBehaviour {
Mesh mesh;
Vector3[] verts;
int[] triangles;
public int xSize = 20;
public int zSize = 20;
private void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>();
CreateShape();
UpdateMesh();
}
void CreateShape()
{
verts = new Vector3[(xSize + 1) * (zSize + 1)];
int i = 0;
for (int z = 0; z <= zSize; z++)
{
for (int x = 0; x <= xSize; x++)
{
verts[i] = new Vector3(x, 0, z);
i++;
}
}
triangles = new int[xSize * zSize * 6];
int vert = 0;
int tris = 0;
for (int z = 0; z < zSize; z++)
{
for (int x = 0; x < xSize; x++)
{
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + xSize + 1;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 4] = vert + xSize + 1;
triangles[tris + 5] = vert + xSize + 2;
vert++;
tris += 6;
}
vert++;
}
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = verts;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
private void OnDrawGizmos()
{
if(verts == null)
{
return;
}
for (int i = 0; i < verts.Length; i++)
{
Gizmos.DrawSphere(verts[i], .1f);
}
}
}
Answer by Bunny83 · Feb 01, 2020 at 12:41 AM
Uhm, you never assigned your mesh to your MeshFilter component. You call GetComponent<MeshFilter>()
in Start wtithout doing anything with it. You probably wanted to do
GetComponent<MeshFilter>().sharedMesh = mesh;
Turns out late night coding you are bound to get mistakes. Thanks Bunny83 it worked perfectly
I had a similar issue on a very similar setup but I was assigning the mesh.
For whatever reason had to remove the script on the game object then reattach the script component. The inspector then loaded the "Required" components.
The reason is quite simple. The RequiredComponents attribute is a pure editor feature that only takes action in the moment when you attach the script to a gameobject in the editor. It does nothing if you add this attribute when the script is already attached. It also does nothing when you add your component through scripting by AddComponent. This is just a convenient WYSIWYG feature. If you were missing a MeshFilter and a MeshRenderer component, you would have to attach them manually. Though your case is very different from the questio the OP as posted, since we can clearly see that the object does have all those components attached.
Follow this Question
Related Questions
Destroy shattered objects after being smashed. 0 Answers
Open canvas clicking on a mesh? 1 Answer
Changing a mesh with C# and Resource.Load() 0 Answers
Using Zed Camera Mesh Maker VR 0 Answers
Mesh missing in prefab 0 Answers