用unity做了一个3D俄罗斯方块的游戏,七个方块都是Prefab,每个俄罗斯方块又由四个cube组成,他们都绑定了同一个脚本,该脚本实现方块的下落和合法性检测等功能。但运行时第一个方块降落后,第二个方块及往后都不能正常降落。尝试打印信息后发现,在合法性检测那里遍历transform的所有child的时候,第一个方块的child也会被包含进去;在尝试对第一个方块进行销毁(从场景中消失)后,之后的方块能正常下落,但这样就不是俄罗斯方块游戏了,有没有什么办法在不让前边的方块在场景中消失的情况下解决问题。
private bool IsValidGridPos()
{
//Debug.Log(this.transform.name);
foreach (Transform child in transform)
{
Debug.Log(this.transform.name);
Debug.Log(child.name);
Vector2 v = MyGrid.Instance.RoundVector2(child.position);
Debug.Log("v:" + v);
if (!MyGrid.Instance.IsInside(v))
{
Debug.Log("222222");
// Debug.Log(this.gameObject.name);
return false;
}
if (MyGrid.Instance.grid[(int)v.x, (int)v.y] != null && MyGrid.Instance.grid[(int)v.x, (int)v.y].parent != this.transform)
{
// Debug.Log(this.gameObject.name);
return false;
}
}
return true;
}
//方块下落
void Fall()
{
if((Time.time -lastFallTime)>FindObjectOfType<Queue>().TimeFrame)
{
transform.position -= new Vector3(0, 1, 0);//让其下落
Debug.Log("position:" + transform.position);
Debug.Log(this.transform.name);
//位置合法性检测
if (IsValidGridPos())
{//位置合法
Debug.Log("合法");
UpdateGrid();
}
else
{//位置不合法,代表方块降落到底部
Debug.Log("不合法");
transform.position += new Vector3(0, 1, 0);
MyGrid.Instance.DeleteFullRows();
// GameObject.Find(objName).GetComponent<ARGroups>().enabled = false;
//Destroy(gameObject);
gameObject.GetComponent<ARGroups>().enabled = false;
FindObjectOfType<Spanwer>().SpawnNext();//生成新的方块
// grandFa = GetComponentsInChildren<Transform>();
// enabled = false;//控制移动和选择的功能不能用了
}
lastFallTime = Time.time;//更新上一次下落的时间为当前时间
}
}