如何在网格布局中获取对象的实际位置?在我当前的迭代中,symbolPosition不断返回0,0,0。
public void OnPointerClick (PointerEventData eventData)
{
// Instantiate an object on click and parent to grid
symbolCharacter = Instantiate(Resources.Load ("Prefabs/Symbols/SymbolImage1")) as GameObject;
symbolCharacter.transform.SetParent(GameObject.FindGameObjectWithTag("MessagePanel").transform);
// Set scale of all objects added
symbolCharacter.transform.localScale = symbolScale;
// Find position of objects in grid
symbolPosition = symbolCharacter.transform.position;
Debug.Log(symbolPosition);
}
答案 0 :(得分:6)
在下一帧之前,位置值不会更新。为了允许您进行大量更改而不会导致对这些元素进行全部重新计算,它会存储需要计算的项目,然后在下一帧的开头更新它们。
所以选择是使用Coroutine等待一个帧然后获得位置
public void OnPointerClick (PointerEventData eventData)
{
// Instantiate an object on click and parent to grid
symbolCharacter = Instantiate(Resources.Load ("Prefabs/Symbols/SymbolImage1")) as GameObject;
symbolCharacter.transform.SetParent(GameObject.FindGameObjectWithTag("MessagePanel").transform);
// Set scale of all objects added
symbolCharacter.transform.localScale = symbolScale;
StartCoroutine(CoWaitForPosition());
}
IEnumerator CoWaitForPosition()
{
yield return new WaitForEndOfFrame();
// Find position of objects in grid
symbolPosition = symbolCharacter.transform.position;
Debug.Log(symbolPosition);
}
答案 1 :(得分:1)
几年前这个问题被提出/回答时,这可能不在API中,但这似乎可以强制GridLayoutGroup将子对象放在添加了子对象的帧上,从而删除了需要一个协程。
for(int i = 0; i < 25; i++){
GameObject gridCell = Instantiate(_gridCellPrefab);
gridCell.transform.SetParent(_gridLayoutTransform,false);
}
_gridLayoutGroup.CalculateLayoutInputHorizontal();
_gridLayoutGroup.CalculateLayoutInputVertical();
_gridLayoutGroup.SetLayoutHorizontal();
_gridLayoutGroup.SetLayoutVertical();
从这里,您可以获得'gridCells'相同帧的位置。
还有另一个功能,它似乎应该达到这个目的,但它对我不起作用。关于内部究竟发生了什么,API非常安静:
LayoutRebuilder.ForceRebuildLayoutImmediate(_gridLayoutTransform);