用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;//更新上一次下落的时间为当前时间
}
}
降落后的方块做检测,脚本隐藏或删除,在合法性检测子物体那里,加个获取脚本判断,第一个方块就不会包含了。
合法检测中落地Destroy( gameObject.GetComponent());
然后上面遍历加if(tranform.GetComponent()!=null)再执行其他代码
不是很理解 这句话 "遍历transform的所有child的时候,第一个方块的child也会被包含进去 " , 意思是你遍历 b 物体的时候log会包含a 的child?
在脚本加个标志符,表示方块状态,未下落,下落中,已落地。遍历的时候根据标志服选择是否要处理
兄弟解决了嘛?我也遇到这种问题,实例化的怪物和角色碰撞时,怪物都会受到同一掉血代码影响