- Home /
Tell an object that a position in grid is occupied
I have built a grid with some nulls(called nulos here) to keep track of positions and if they are occupied by another object:
private void Init()
{
matriz = new int[3, 3, 3];
nulos = new GameObject[27];
int n = 0;
for (int i = 0; i < nulos.Length; i++)
nulos[i] = Instantiate(nulo);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++)
{
nulos[n].transform.position = new Vector3(nulos[n].transform.position.x + i, nulos[n].transform.position.y + j, nulos[n].transform.position.z + k);
Cubo = nulos[n].GetComponent<CubeProperties>();
nulos[n].name = i.ToString() + j.ToString() + k.ToString();
n++;
}
}
"Cubo" contains a script called CubeProperties that has a bool "free" that I'm using to check if the position a block is trying to move to its already in use.
In each object/block in my grid I have a script called "movingCube" that has a method moveIt called in update:
void Start()
{
GameObject.Find(x.ToString() + y.ToString() + z.ToString()).GetComponent<CubeProperties>().free = false;
}
public void moveIt()
{
if (Input.GetKeyDown(KeyCode.W))
{
if (GameObject.Find((x + 1).ToString() + y.ToString() + z.ToString()) != null)
{
if (GameObject.Find((x + 1).ToString() + y.ToString() + z.ToString()).GetComponent<CubeProperties>().free == true)
{
transform.position = GameObject.Find((x + 1).ToString() + y.ToString() + z.ToString()).GetComponent<CubeProperties>().transform.position;
GameObject.Find(x.ToString() + y.ToString() + z.ToString()).GetComponent<CubeProperties>().free = true;
GameObject.Find((x + 1).ToString() + y.ToString() + z.ToString()).GetComponent<CubeProperties>().free = false;
x++;
}
}
}
The problem is: I though that by asking
if (GameObject.Find((x + 1).ToString() + y.ToString() + z.ToString()).GetComponent().free == true)
it wouldit would let me move only if the space was not already occupied by another object, but right now it does nothing as it allows me to move without recognizing the other objects and overlapping them.
At start each cube tells the grid their initial position, so I don't see why it is not working? Any insight of what I've done wrong?
how and where are you assigning the .free value? I don't see that in the first code block.
It's a convoluted process that you are implementing, but on the surface, I don't see why it would not work, assu$$anonymous$$g that the x, y and z variables are being set to your transform positions x,y and z values before moveIt is called. Have you confirmed in the inspector at runtime, that the Free boolean is being set as expected?