Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question object reference not set to an instance of an object unity

Discussion in 'Scripting' started by SeraJudesa, Apr 25, 2022.

  1. SeraJudesa

    SeraJudesa

    Joined:
    Mar 24, 2022
    Posts:
    1
    Hi all,

    I have been following CatLike Coding's Hexmap tutorials to create my Hexmap based game. Recently I have encountered these errors :


    NullReferenceException: Object reference not set to an instance of an object
    HexMesh.Triangulate (HexDirection direction, HexCell cell) (at Assets/Scripts/HexMesh.cs:43)
    HexMesh.Triangulate (HexCell cell) (at Assets/Scripts/HexMesh.cs:38)
    HexMesh.Triangulate (HexCell[] cells) (at Assets/Scripts/HexMesh.cs:27)
    HexGridChunk.LateUpdate () (at Assets/Scripts/HexGridChunk.cs:37)



    I have tried to find the source of these error. From what I read is that the object needs to be instantiated but I don't see any other variables doing the this and I have followed the tutorial to the T. Can anyone provide a view from another angle to see what I am doing wrong?

    Here are the HexMesh.cs and HexGridChunk.cs:

    HexMesh.cs
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    3.  
    4. [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
    5. public class HexMesh : MonoBehaviour {
    6.  
    7.     static List<Vector3> vertices = new List<Vector3>();
    8.     static List<Color> colors = new List<Color>();
    9.     static List<int> triangles = new List<int>();
    10.  
    11.     Mesh hexMesh;
    12.     MeshCollider meshCollider;
    13.    
    14.  
    15.     void Awake () {
    16.         GetComponent<MeshFilter>().mesh = hexMesh = new Mesh();
    17.         meshCollider = gameObject.AddComponent<MeshCollider>();
    18.         hexMesh.name = "Hex Mesh";
    19.     }
    20.  
    21.     public void Triangulate (HexCell[] cells) {
    22.         hexMesh.Clear();
    23.         vertices.Clear();
    24.         colors.Clear();
    25.         triangles.Clear();
    26.         for (int i = 0; i < cells.Length; i++) {
    27.             Triangulate(cells[i]);
    28.         }
    29.         hexMesh.vertices = vertices.ToArray();
    30.         hexMesh.colors = colors.ToArray();
    31.         hexMesh.triangles = triangles.ToArray();
    32.         hexMesh.RecalculateNormals();
    33.         meshCollider.sharedMesh = hexMesh;
    34.     }
    35.  
    36.     void Triangulate (HexCell cell) {
    37.         for (HexDirection d = HexDirection.NE; d <= HexDirection.NW; d++) {
    38.             Triangulate(d, cell);
    39.         }
    40.     }
    41.  
    42.     void Triangulate (HexDirection direction, HexCell cell) {
    43.         Vector3 center = cell.Position;
    44.         EdgeVertices e = new EdgeVertices(
    45.             center + HexMetrics.GetFirstSolidCorner(direction),
    46.             center + HexMetrics.GetSecondSolidCorner(direction)
    47.         );
    48.  
    49.         TriangulateEdgeFan(center, e, cell.Color);
    50.  
    51.         if (direction <= HexDirection.SE) {
    52.             TriangulateConnection(direction, cell, e);
    53.         }
    54.     }
    55.  
    56.     void TriangulateConnection (
    57.         HexDirection direction, HexCell cell, EdgeVertices e1
    58.     ) {
    59.         HexCell neighbor = cell.GetNeighbor(direction);
    60.         if (neighbor == null) {
    61.             return;
    62.         }
    63.  
    64.         Vector3 bridge = HexMetrics.GetBridge(direction);
    65.         bridge.y = neighbor.Position.y - cell.Position.y;
    66.         EdgeVertices e2 = new EdgeVertices(
    67.             e1.v1 + bridge,
    68.             e1.v4 + bridge
    69.         );
    70.  
    71.         if (cell.GetEdgeType(direction) == HexEdgeType.Slope) {
    72.             TriangulateEdgeTerraces(e1, cell, e2, neighbor);
    73.         }
    74.         else {
    75.             TriangulateEdgeStrip(e1, cell.Color, e2, neighbor.Color);
    76.         }
    77.  
    78.         HexCell nextNeighbor = cell.GetNeighbor(direction.Next());
    79.         if (direction <= HexDirection.E && nextNeighbor != null) {
    80.             Vector3 v5 = e1.v4 + HexMetrics.GetBridge(direction.Next());
    81.             v5.y = nextNeighbor.Position.y;
    82.  
    83.             if (cell.Elevation <= neighbor.Elevation) {
    84.                 if (cell.Elevation <= nextNeighbor.Elevation) {
    85.                     TriangulateCorner(
    86.                         e1.v4, cell, e2.v4, neighbor, v5, nextNeighbor
    87.                     );
    88.                 }
    89.                 else {
    90.                     TriangulateCorner(
    91.                         v5, nextNeighbor, e1.v4, cell, e2.v4, neighbor
    92.                     );
    93.                 }
    94.             }
    95.             else if (neighbor.Elevation <= nextNeighbor.Elevation) {
    96.                 TriangulateCorner(
    97.                     e2.v4, neighbor, v5, nextNeighbor, e1.v4, cell
    98.                 );
    99.             }
    100.             else {
    101.                 TriangulateCorner(
    102.                     v5, nextNeighbor, e1.v4, cell, e2.v4, neighbor
    103.                 );
    104.             }
    105.         }
    106.     }
    107.  
    108.     void TriangulateCorner (
    109.         Vector3 bottom, HexCell bottomCell,
    110.         Vector3 left, HexCell leftCell,
    111.         Vector3 right, HexCell rightCell
    112.     ) {
    113.         HexEdgeType leftEdgeType = bottomCell.GetEdgeType(leftCell);
    114.         HexEdgeType rightEdgeType = bottomCell.GetEdgeType(rightCell);
    115.  
    116.         if (leftEdgeType == HexEdgeType.Slope) {
    117.             if (rightEdgeType == HexEdgeType.Slope) {
    118.                 TriangulateCornerTerraces(
    119.                     bottom, bottomCell, left, leftCell, right, rightCell
    120.                 );
    121.             }
    122.             else if (rightEdgeType == HexEdgeType.Flat) {
    123.                 TriangulateCornerTerraces(
    124.                     left, leftCell, right, rightCell, bottom, bottomCell
    125.                 );
    126.             }
    127.             else {
    128.                 TriangulateCornerTerracesCliff(
    129.                     bottom, bottomCell, left, leftCell, right, rightCell
    130.                 );
    131.             }
    132.         }
    133.         else if (rightEdgeType == HexEdgeType.Slope) {
    134.             if (leftEdgeType == HexEdgeType.Flat) {
    135.                 TriangulateCornerTerraces(
    136.                     right, rightCell, bottom, bottomCell, left, leftCell
    137.                 );
    138.             }
    139.             else {
    140.                 TriangulateCornerCliffTerraces(
    141.                     bottom, bottomCell, left, leftCell, right, rightCell
    142.                 );
    143.             }
    144.         }
    145.         else if (leftCell.GetEdgeType(rightCell) == HexEdgeType.Slope) {
    146.             if (leftCell.Elevation < rightCell.Elevation) {
    147.                 TriangulateCornerCliffTerraces(
    148.                     right, rightCell, bottom, bottomCell, left, leftCell
    149.                 );
    150.             }
    151.             else {
    152.                 TriangulateCornerTerracesCliff(
    153.                     left, leftCell, right, rightCell, bottom, bottomCell
    154.                 );
    155.             }
    156.         }
    157.         else {
    158.             AddTriangle(bottom, left, right);
    159.             AddTriangleColor(bottomCell.Color, leftCell.Color, rightCell.Color);
    160.         }
    161.     }
    162.  
    163.     void TriangulateEdgeTerraces (
    164.         EdgeVertices begin, HexCell beginCell,
    165.         EdgeVertices end, HexCell endCell
    166.     ) {
    167.         EdgeVertices e2 = EdgeVertices.TerraceLerp(begin, end, 1);
    168.         Color c2 = HexMetrics.TerraceLerp(beginCell.Color, endCell.Color, 1);
    169.  
    170.         TriangulateEdgeStrip(begin, beginCell.Color, e2, c2);
    171.  
    172.         for (int i = 2; i < HexMetrics.terraceSteps; i++) {
    173.             EdgeVertices e1 = e2;
    174.             Color c1 = c2;
    175.             e2 = EdgeVertices.TerraceLerp(begin, end, i);
    176.             c2 = HexMetrics.TerraceLerp(beginCell.Color, endCell.Color, i);
    177.             TriangulateEdgeStrip(e1, c1, e2, c2);
    178.         }
    179.  
    180.         TriangulateEdgeStrip(e2, c2, end, endCell.Color);
    181.     }
    182.  
    183.     void TriangulateCornerTerraces (
    184.         Vector3 begin, HexCell beginCell,
    185.         Vector3 left, HexCell leftCell,
    186.         Vector3 right, HexCell rightCell
    187.     ) {
    188.         Vector3 v3 = HexMetrics.TerraceLerp(begin, left, 1);
    189.         Vector3 v4 = HexMetrics.TerraceLerp(begin, right, 1);
    190.         Color c3 = HexMetrics.TerraceLerp(beginCell.Color, leftCell.Color, 1);
    191.         Color c4 = HexMetrics.TerraceLerp(beginCell.Color, rightCell.Color, 1);
    192.  
    193.         AddTriangle(begin, v3, v4);
    194.         AddTriangleColor(beginCell.Color, c3, c4);
    195.  
    196.         for (int i = 2; i < HexMetrics.terraceSteps; i++) {
    197.             Vector3 v1 = v3;
    198.             Vector3 v2 = v4;
    199.             Color c1 = c3;
    200.             Color c2 = c4;
    201.             v3 = HexMetrics.TerraceLerp(begin, left, i);
    202.             v4 = HexMetrics.TerraceLerp(begin, right, i);
    203.             c3 = HexMetrics.TerraceLerp(beginCell.Color, leftCell.Color, i);
    204.             c4 = HexMetrics.TerraceLerp(beginCell.Color, rightCell.Color, i);
    205.             AddQuad(v1, v2, v3, v4);
    206.             AddQuadColor(c1, c2, c3, c4);
    207.         }
    208.  
    209.         AddQuad(v3, v4, left, right);
    210.         AddQuadColor(c3, c4, leftCell.Color, rightCell.Color);
    211.     }
    212.  
    213.     void TriangulateCornerTerracesCliff (
    214.         Vector3 begin, HexCell beginCell,
    215.         Vector3 left, HexCell leftCell,
    216.         Vector3 right, HexCell rightCell
    217.     ) {
    218.         float b = 1f / (rightCell.Elevation - beginCell.Elevation);
    219.         if (b < 0) {
    220.             b = -b;
    221.         }
    222.         Vector3 boundary = Vector3.Lerp(Perturb(begin), Perturb(right), b);
    223.         Color boundaryColor = Color.Lerp(beginCell.Color, rightCell.Color, b);
    224.  
    225.         TriangulateBoundaryTriangle(
    226.             begin, beginCell, left, leftCell, boundary, boundaryColor
    227.         );
    228.  
    229.         if (leftCell.GetEdgeType(rightCell) == HexEdgeType.Slope) {
    230.             TriangulateBoundaryTriangle(
    231.                 left, leftCell, right, rightCell, boundary, boundaryColor
    232.             );
    233.         }
    234.         else {
    235.             AddTriangleUnperturbed(Perturb(left), Perturb(right), boundary);
    236.             AddTriangleColor(leftCell.Color, rightCell.Color, boundaryColor);
    237.         }
    238.     }
    239.  
    240.     void TriangulateCornerCliffTerraces (
    241.         Vector3 begin, HexCell beginCell,
    242.         Vector3 left, HexCell leftCell,
    243.         Vector3 right, HexCell rightCell
    244.     ) {
    245.         float b = 1f / (leftCell.Elevation - beginCell.Elevation);
    246.         if (b < 0) {
    247.             b = -b;
    248.         }
    249.         Vector3 boundary = Vector3.Lerp(Perturb(begin), Perturb(left), b);
    250.         Color boundaryColor = Color.Lerp(beginCell.Color, leftCell.Color, b);
    251.  
    252.         TriangulateBoundaryTriangle(
    253.             right, rightCell, begin, beginCell, boundary, boundaryColor
    254.         );
    255.  
    256.         if (leftCell.GetEdgeType(rightCell) == HexEdgeType.Slope) {
    257.             TriangulateBoundaryTriangle(
    258.                 left, leftCell, right, rightCell, boundary, boundaryColor
    259.             );
    260.         }
    261.         else {
    262.             AddTriangleUnperturbed(Perturb(left), Perturb(right), boundary);
    263.             AddTriangleColor(leftCell.Color, rightCell.Color, boundaryColor);
    264.         }
    265.     }
    266.  
    267.     void TriangulateBoundaryTriangle (
    268.         Vector3 begin, HexCell beginCell,
    269.         Vector3 left, HexCell leftCell,
    270.         Vector3 boundary, Color boundaryColor
    271.     ) {
    272.         Vector3 v2 = Perturb(HexMetrics.TerraceLerp(begin, left, 1));
    273.         Color c2 = HexMetrics.TerraceLerp(beginCell.Color, leftCell.Color, 1);
    274.  
    275.         AddTriangleUnperturbed(Perturb(begin), v2, boundary);
    276.         AddTriangleColor(beginCell.Color, c2, boundaryColor);
    277.  
    278.         for (int i = 2; i < HexMetrics.terraceSteps; i++) {
    279.             Vector3 v1 = v2;
    280.             Color c1 = c2;
    281.             v2 = Perturb(HexMetrics.TerraceLerp(begin, left, i));
    282.             c2 = HexMetrics.TerraceLerp(beginCell.Color, leftCell.Color, i);
    283.             AddTriangleUnperturbed(v1, v2, boundary);
    284.             AddTriangleColor(c1, c2, boundaryColor);
    285.         }
    286.  
    287.         AddTriangleUnperturbed(v2, Perturb(left), boundary);
    288.         AddTriangleColor(c2, leftCell.Color, boundaryColor);
    289.     }
    290.  
    291.     void TriangulateEdgeFan (Vector3 center, EdgeVertices edge, Color color) {
    292.         AddTriangle(center, edge.v1, edge.v2);
    293.         AddTriangleColor(color);
    294.         AddTriangle(center, edge.v2, edge.v3);
    295.         AddTriangleColor(color);
    296.         AddTriangle(center, edge.v3, edge.v4);
    297.         AddTriangleColor(color);
    298.     }
    299.  
    300.     void TriangulateEdgeStrip (
    301.         EdgeVertices e1, Color c1,
    302.         EdgeVertices e2, Color c2
    303.     ) {
    304.         AddQuad(e1.v1, e1.v2, e2.v1, e2.v2);
    305.         AddQuadColor(c1, c2);
    306.         AddQuad(e1.v2, e1.v3, e2.v2, e2.v3);
    307.         AddQuadColor(c1, c2);
    308.         AddQuad(e1.v3, e1.v4, e2.v3, e2.v4);
    309.         AddQuadColor(c1, c2);
    310.     }
    311.  
    312.     void AddTriangle (Vector3 v1, Vector3 v2, Vector3 v3) {
    313.         int vertexIndex = vertices.Count;
    314.         vertices.Add(Perturb(v1));
    315.         vertices.Add(Perturb(v2));
    316.         vertices.Add(Perturb(v3));
    317.         triangles.Add(vertexIndex);
    318.         triangles.Add(vertexIndex + 1);
    319.         triangles.Add(vertexIndex + 2);
    320.     }
    321.  
    322.     void AddTriangleUnperturbed (Vector3 v1, Vector3 v2, Vector3 v3) {
    323.         int vertexIndex = vertices.Count;
    324.         vertices.Add(v1);
    325.         vertices.Add(v2);
    326.         vertices.Add(v3);
    327.         triangles.Add(vertexIndex);
    328.         triangles.Add(vertexIndex + 1);
    329.         triangles.Add(vertexIndex + 2);
    330.     }
    331.  
    332.     void AddTriangleColor (Color color) {
    333.         colors.Add(color);
    334.         colors.Add(color);
    335.         colors.Add(color);
    336.     }
    337.  
    338.     void AddTriangleColor (Color c1, Color c2, Color c3) {
    339.         colors.Add(c1);
    340.         colors.Add(c2);
    341.         colors.Add(c3);
    342.     }
    343.  
    344.     void AddQuad (Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4) {
    345.         int vertexIndex = vertices.Count;
    346.         vertices.Add(Perturb(v1));
    347.         vertices.Add(Perturb(v2));
    348.         vertices.Add(Perturb(v3));
    349.         vertices.Add(Perturb(v4));
    350.         triangles.Add(vertexIndex);
    351.         triangles.Add(vertexIndex + 2);
    352.         triangles.Add(vertexIndex + 1);
    353.         triangles.Add(vertexIndex + 1);
    354.         triangles.Add(vertexIndex + 2);
    355.         triangles.Add(vertexIndex + 3);
    356.     }
    357.  
    358.     void AddQuadColor (Color c1, Color c2) {
    359.         colors.Add(c1);
    360.         colors.Add(c1);
    361.         colors.Add(c2);
    362.         colors.Add(c2);
    363.     }
    364.  
    365.     void AddQuadColor (Color c1, Color c2, Color c3, Color c4) {
    366.         colors.Add(c1);
    367.         colors.Add(c2);
    368.         colors.Add(c3);
    369.         colors.Add(c4);
    370.     }
    371.  
    372.     Vector3 Perturb (Vector3 position) {
    373.         Vector4 sample = HexMetrics.SampleNoise(position);
    374.         position.x += (sample.x * 2f - 1f) * HexMetrics.cellPerturbStrength;
    375.         position.z += (sample.z * 2f - 1f) * HexMetrics.cellPerturbStrength;
    376.         return position;
    377.     }
    378. }
    HexGridChunk.cs:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class HexGridChunk : MonoBehaviour {
    5.  
    6.     HexCell[] cells;
    7.    
    8.    
    9.  
    10.     HexMesh hexMesh;
    11.     Canvas gridCanvas;
    12.  
    13.     void Awake () {
    14.         gridCanvas = GetComponentInChildren<Canvas>();
    15.         hexMesh = GetComponentInChildren<HexMesh>();
    16.  
    17.         cells = new HexCell[HexMetrics.chunkSizeX * HexMetrics.chunkSizeZ];
    18.         ShowUI(false);
    19.     }
    20.  
    21.     public void AddCell (int index, HexCell cell) {
    22.         cells[index] = cell;
    23.         cell.chunk = this;
    24.         cell.transform.SetParent(transform, false);
    25.         cell.uiRect.SetParent(gridCanvas.transform, false);
    26.     }
    27.  
    28.     public void Refresh () {
    29.         enabled = true;
    30.     }
    31.  
    32.     public void ShowUI (bool visible) {
    33.         gridCanvas.gameObject.SetActive(visible);
    34.     }
    35.  
    36.     void LateUpdate () {
    37.         hexMesh.Triangulate(cells);
    38.         enabled = false;
    39.     }
    40. }
     
  2. nijnstein

    nijnstein

    Joined:
    Feb 6, 2021
    Posts:
    78
    there is a function addcell in hexgridchunk.cs

    i cannot find a call to it in your code

    it would explain the null reference if you dont setup the cells

    you declare an array of cells but these would all be null objects
     
  3. SourGummi

    SourGummi

    Joined:
    Nov 14, 2021
    Posts:
    96
    ERROR
    NullReferenceException: Object reference not set to an instance of an object



    in this case; Material being null will look like


    so in your code youre making a variable of say Material
    new_material;
    but youre never setting the value of your material.

    Code (CSharp):
    1. new_material = new(material2);

    so find where youre creating a new variable, that you never set a value for, then try to call that variable elsewhere.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,710
    The answer for this is ALWAYS the same, always. It's so common there is a pinned post!

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Steps to success:
    - Identify what is null
    - Identify why it is null
    - Fix that

    If you are having trouble sequencing out why, use this approach:

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    You must find a way to get the information you need in order to reason about what the problem is.