Looking through all the children doesn't work
Hello, I'm making Tetris and I need to detect the collisions with every piece. For that, I'm using:
foreach (Transform child in transform)
But it just detects one child.
My code looks like this
bool ValidMove()
{
foreach (Transform child in transform)
{
int roundedX = Mathf.RoundToInt(child.transform.position.x);
int roundedY = Mathf.RoundToInt(child.transform.position.y);
if (roundedX < -10 || roundedX >= 0 || roundedY < 0 || grid[roundedX, roundedY] != null)
return false;
}
return true;
}
}
and I have another piece that looks like this
void AddToGrid()
{
foreach(Transform child in transform)
{
int roundedX = Mathf.RoundToInt(child.transform.position.x);
int roundedY = Mathf.RoundToInt(child.transform.position.y);
grid[roundedX, roundedY] = child;
}
}
None of them work. They detect just one piece of the 4 that all the tetrominos have.
Thank you in advance.
Comment
Hi, Give this a try so you can debug what's happening better
void TraverseChildren(Transform parent)
{
for (int i = 0; i <parent.childCount; i++)
{
Debug.Log(parent.GetChild(i).name);
}
}
Then grow to also print roundedX and roundedY.
But I also see a problem with the look-up. If roundedX is -9, you'll try to lookup grid[-9].
Answer by Tsaras · May 24, 2019 at 07:26 PM
Replace your code with the following loop:
bool ValidMove()
{
int childCount = transform.childCount;
for (int i=0; i <= childCount ; i++)
{
Transform child = transform.GetChild(i);
int roundedX = Mathf.RoundToInt(child.transform.position.x);
int roundedY = Mathf.RoundToInt(child.transform.position.y);
if (roundedX < -10 || roundedX >= 0 || roundedY < 0 || grid[roundedX, roundedY] != null)
return false;
}
return true;
}
Your answer
Follow this Question
Related Questions
Can't get Child's Child 0 Answers
For and Foreach not getting all child transform 0 Answers
Child object in animation transform Problems 1 Answer