- Home /
Null Reference Exception Assigning Vertices to Mesh
I am getting a Null Reference Exception during runtime on the line where I assign the vertices to the mesh here is the code...
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
[RequireComponent (typeof (MeshCollider))]
[RequireComponent (typeof (MeshFilter))]
[RequireComponent (typeof (MeshRenderer))]
public class Geometric: MonoBehaviour
{
public float blockheight = 1.0f;
public Material blockmaterial;
public PhysicMaterial physical;
public MeshRenderer meshrenderer;
public GameObject newbox;
public int t = 0;
void Update()
{
t++;
if(t == 5)
CreateBox();
}
public void CreateBox()
{
Vector3 p1 = new Vector3(0,0,0);
Vector3 p2 = new Vector3(4,0,0);
MeshFilter meshFilter = GetComponent<MeshFilter>();
Mesh newmesh = meshFilter.sharedMesh;
//newmesh.Clear();
//FIND SOME VERTICES
//wherever p is located the z plane will be placed realtive to the coordinate
Vector3 topLeftFront = p1;
Vector3 topRightFront = p2;
Vector3 topLeftBack = p1;
Vector3 topRightBack = p2;
topRightFront.z =.5f;
topLeftFront.z = .5f;
topLeftBack.z = -.5f;
topRightBack.z = -.5f;
//copy some coordinates to alter from previois vertices assignments
Vector3 bottomLeftFront = topLeftFront;
Vector3 bottomRightFront = topRightFront;
Vector3 bottomLeftBack = bottomLeftFront;
Vector3 bottomRightBack = bottomRightFront;
bottomLeftBack.y = bottomLeftFront.y = bottomRightBack.y = bottomRightFront.y = -1*blockheight;
//assign the vertex positions to the mesh vertices array
newmesh.vertices = new Vector3[]{topLeftFront,topRightFront,topLeftBack,topRightBack,bottomLeftFront,
bottomRightFront,bottomLeftBack,bottomRightBack};
//assign uvs based on vertices in array?
Vector2[] uvs = new Vector2[newmesh.vertices.Length];
for(int i=0; i < newmesh.vertices.Length; i++)
{
Debug.Log(newmesh.vertices[i]);
uvs[i] = new Vector2(newmesh.vertices[i].x, newmesh.vertices[i].z);
}
newmesh.uv = uvs;
//group sets of 3 vertices into triagles endpoints
newmesh.triangles = new int[]{0,1,5,1,5,6,0,2,3,2,3,1,2,0,4,0,4,6,2,3,7,3,7,4,3,1,5,1,5,7,4,6,7,6,7,5};
//box the mesh
newmesh.RecalculateNormals();
newmesh.RecalculateBounds();
newmesh.Optimize();
}
}
Comment
So 'newmesh' is null, right? And that means 'meshFilter.shared$$anonymous$$esh' is also null.
... and that means there is no $$anonymous$$esh object so you have to create one.
newmesh = new $$anonymous$$esh();
//...
meshFilter.shared$$anonymous$$esh = newmesh;
Your answer
Follow this Question
Related Questions
Huge GC Overhead When Accessing Tris/Verts From Mesh? 2 Answers
Accessing Mesh: Triangle and Vertex array fields directly? 0 Answers
Why does the default Unity sphere have duplicate vertices? 1 Answer
Problem Creating a 2D Mesh 1 Answer
Procedural Mesh Generation - Split Arrays into sections 1 Answer