I am trying to make a 5x4 grid based game with jellyfish gameobjects rock gameobject and blank spaces.
I need help finding a way to attach these objects to a 2d array so that I can later move them in the grid.
Each level in the game is going to start with the jellyfish and rocks in different spaces so if possible I need an array that can get the gameobjects based on position.
I am using c# for my code.
Not sure what the question here really is. Typically you’d want all of the objects in the grid to have a script that can store their grid coordinates and type
public enum ItemType {
Rock,
Jelly,
Blank
}
public class RockJellyOrBlank : MonoBehaviour {
public ItemType Type;
public int X;
public int Y;
public void SetCoords(int x, int y) {
X = x;
Y = y;
transform.position = new Vector3(X, Y, 0); // some multiplier here to get wanted spacing
}
}
Then have a class with an array that holds these objects and the methods for finding and moving objects around in the grid.
public RockJellyOrBlank[] Items;
public int Rows;
public int Columns;
void Start(){
Items = new RockJellyOrBlank[Rows * Columns];
}
public RockJellyOrBlank GetItemAtCoordinates(int x, int y){
return Items[x + y * Columns];
}
When an object is clicked for example, you can then get the RockJellyOrBlank script from the clicked object and then calculate theindex it is in based on its X and Y and move it to anothe grid cell for example
very simple just make your jelly fish have a tag and it doesnt matter if it instansiated on runtime
this will return all the objects that are on the scene and have a tag of “myJellyFish”
and then to access position
GameObject[] myJellies = GameObject.FindGameObjectsWithTag("myJellyFish");
if (myJellies.length > 0)
print(myJellies[0].transform.position);