Object reference not set to an instance of an object. Array

0

Hi, My problem is in the array following this code:

mesh meshCube;
string[] file = File.ReadAllLines("object.mind");
foreach (string filetext in file)
{
    if (filetext.Contains("v"))
    {
        string ext = filetext.Substring(filetext.IndexOf(" ") + 1);
        string[] pos = ext.Split(' ');
        // erro nessa linha ↓
        meshCube.tris.Add( new triangle (
            new vec3d(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2])),
            new vec3d(float.Parse(pos[3]), float.Parse(pos[4]), float.Parse(pos[5])),
            new vec3d(float.Parse(pos[6]), float.Parse(pos[7]), float.Parse(pos[8])))
        );
     }
}

public class vec3d
{
    public vec3d(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }
}
public class triangle
{
    public triangle(vec3d one, vec3d two, vec3d three)
    {
        p = new[] { one, two, three };
    }
    public vec3d[] p = new vec3d[3];
}
public class mesh
{
    public List<triangle> tris = new List<triangle>();
}
    
asked by anonymous 24.10.2018 / 00:21

1 answer

1

You declared the variable meshCube but did not load the variable with any object, so it gives the error NullPointerException when trying to use it:

mesh meshCube;

// [...]

        // erro nessa linha ↓
        meshCube.tris.Add( new triangle (
            new vec3d(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2])),
            new vec3d(float.Parse(pos[3]), float.Parse(pos[4]), float.Parse(pos[5])),
            new vec3d(float.Parse(pos[6]), float.Parse(pos[7]), float.Parse(pos[8])))
        );

Declare this way you should solve this problem:

mesh meshCube = new mesh();

It is worth mentioning that it would be interesting to check if the pos array contains the number of items needed before to use it:

if (filetext.Contains("v"))
{
    string ext = filetext.Substring(filetext.IndexOf(" ") + 1);
    string[] pos = ext.Split(' ');
    // Verifica se o array contém a quantidade adequada de itens.
    if (pos.Length == 9)
    {
        meshCube.tris.Add( new triangle (
            new vec3d(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2])),
            new vec3d(float.Parse(pos[3]), float.Parse(pos[4]), float.Parse(pos[5])),
            new vec3d(float.Parse(pos[6]), float.Parse(pos[7]), float.Parse(pos[8])))
        );
    }

Because this can cause other errors as well.

    
24.10.2018 / 00:48