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

Trying to keep track of 3D grid

Discussion in 'Scripting' started by _jacks, Sep 8, 2015.

  1. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    Hi,

    So what I want to do is keep track of a 3D grid of objects I will call "Node"

    I have created a Node class and a Grid class of which grid contains an 2D array of Node and I have an array of Grid which _should_ be a 3D cube in memory (or at least thats the way I see it)

    I'm getting really confused with how to access each Node member. It should basically be a 3D cube of nodes in memory that I can loop through. How does one define such a class and access them via some kind of matrix 3d cube if you know what I mean.

    Thanks :)
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Rather than having a complex nest of classes, I'd recommend you build this as a one-dimensional array. (I'm assuming that your Grid class exists solely to store the 2D array of Nodes; if it has other functionality that makes slicing it into grids make sense, ignore this suggestion)

    Your Node array's total size will be L*W*H, and you'll arrange your nodes in it by laying them out row by row. When you access a node at (x,y,z), you should be able to get directly to its index like so:
    Code (csharp):
    1. Node[] nodes = new Node[length * width * height];
    2. int index = z * width * height + y * width + x;
    3. nodes[index] = CreateNewNode();
    I'm assuming that the length, width, and height are all not especially huge (e.g. around 100 nodes on a side or less); if they're much bigger than that, you should use a Dictionary to create a sparse array instead. A fully fleshed out cube that's largely full of empty Nodes would just waste memory. Plus, when you get above around 1500 nodes on a side, you'll start hitting the integer limit on some cells, making it not just a memory hog but will actively cause errors.
     
  3. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    OK I see what you did there.

    So you would use a Dictionary if you had say 8.5 million nodes?

    There wont be much data in the Node class itself thanks