Unity:实例化预制件出现在错误的位置

Unity: Instantiating prefab appears at wrong location

我正在创建一个简单的基于文本的谜题,该谜题将在 运行 时提供各种线索。我想我应该通过实例化一些预制件来做到这一点。这是现在的样子。

注意转换值。资产中的预制件具有完全相同的值。

为了测试是否可以在 运行 时实例化一堆 Puzzle 对象,我创建了这个简单的循环:

     for (int x = 1; x < 6; x++)
     {
         Debug.Log(15-x);
         Instantiate(puzzle, new Vector2(0, 15 - x), Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
     }

想法是所有克隆都将堆叠在第一个 Puzzle 对象下方。但是,当我 运行 它时会发生这种情况:

克隆体堆叠在错误的位置。我使用调试日志来确认向量使用了正确的值,并且我也尝试过使用 Vector3。统一论坛上有很多类似的问题,但是 none 这些解决方案对我有用。任何见解将不胜感激。

要设置 canvas 个元素的位置,您需要使用 anchoredPosition of the RectTransform.

因此您需要获取目标元素的 anchoredPosition,以便您可以根据该位置定位下一个元素。

    public RectTransform firstPuzzle;
    public GameObject puzzle;

    private void InstantiatePuzzle()
    {
        for (int x = 1; x < 6; x++)
        {
            RectTransform spawnedPuzzle = Instantiate(puzzle, GameObject.FindGameObjectWithTag("Canvas").transform).GetComponent<RectTransform>();
            spawnedPuzzle.anchoredPosition = new Vector2(firstPuzzle.anchoredPosition.x, firstPuzzle.anchoredPosition.y - (50 * x));// 50 is the gap you want it to be.
        }
    }

分配当前在检查器中的第一个元素 (Puzzle) 的引用,它将开始以 50 的间距定位下一个元素。

这是输出。