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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Failing hard with class instansing. (solved)

Discussion in 'Scripting' started by jomsa, Oct 1, 2017.

  1. jomsa

    jomsa

    Joined:
    Nov 10, 2013
    Posts:
    23
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class jWater : MonoBehaviour {
    5.  
    6.     public class waterPixel {
    7.         public float amount;
    8.         public float[] flow;
    9.  
    10.         public waterPixel() {
    11.             flow = new float[9];
    12.             amount = 0;
    13.         }
    14.     }
    15.        
    16.     public static waterPixel[,] waterWorld = new waterPixel[WorldData.world_size, WorldData.world_size];
    17.  
    18.     public static void init_water() {
    19.         //de nada
    20.         for (int i = 0; i < WorldData.world_size; i++) {
    21.             for (int j = 0; j < WorldData.world_size; j++) {
    22.                 waterWorld [i, j].amount = 0f;
    23.             }
    24.         }
    25.     }
    26. }
    So, i was hoping to set up a worldmap structure in similar way i used to do it back in C days but with classes. Obviously something is not right here, as i am getting "NullReferenceException: Object reference not set to an instance of an object"... but i thought that the new WaterPixel part there is supposed to create the new instance? Whats going on?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    The array is created but each value inside the array is still null.

    Code (csharp):
    1.  
    2. waterWorld[i,j] = new waterPixel();
    3. waterWorld[i,j].amount = 0f;
    4.  
     
    jomsa likes this.
  3. jomsa

    jomsa

    Joined:
    Nov 10, 2013
    Posts:
    23
    I knew it had to be something simple. Thanks. Though i still wonder if this is the right way to go about this. In general i mean. Having entire worldmap data stored in a such way.