Home > Enterprise >  Grid based detection unity 2d
Grid based detection unity 2d

Time:03-08

I am a bit nooby when it comes to unity. I have no clue where to start with grids. What I am trying to do is make a grid where each gridspot stores all of the gameobject within it in a list/array. Then those same objects can acces that list if they are looking for somthing. Anny suggestions where I can find what I am looking for?

Edit: This is a 2d game but the unity2d tag is showing med unity3d

CodePudding user response:

You can create gridManager class that has 2d array of type gridCell class

public class GridManager : MonoBehaviour
{
    GridCell[,] grid = new grid[5,5];

    void Start()
    {
        grid[1,2] = new GridCell();
        grid[1,2].example = true;

        bool boo = grid[1,2].example;
    }


}

public class GridCell
{
    public bool example;
}

Here we create 5x5 empty grid of type GridCell, then on cords x=1 y=2 we add new GridCell to that place in grid. We add true value to our example value in that cell, and then we read what that value is.

Now you can change that bool variable to array that stores all game object you want. When you adding game object to that array, add reference to GridCell inside game object you storing. To get other stored objects inside that cell, create method inside cell that returns other objects stored inside that array cell. With that, your game object can request a list of other game objects inside same cell

  • Related