【问题标题】:How to set a prefab-cloned object position to (0,0,0) relative to parent?如何将预制克隆的对象位置相对于父对象设置为(0,0,0)?
【发布时间】:2018-01-04 23:05:23
【问题描述】:

我有一个 UI 面板。 在该面板中,我想多次添加相同的预制件(一个小圆圈)。 我的代码如下所示:

GameObject o = GameObject.Find("PanelCells");
Rect r = o.GetComponent<RectTransform>().rect;
RemoveAllChildren(o.transform);
for (float i = 0; i < 10; i += (float)1.0) {
    GameObject c = Instantiate(
        prefabCell, Vector3.zero, Quaternion.identity, o.transform
    );
    c.transform.localScale = new Vector3(1, 1, 1);
    Debug.Log("Before : " + c.transform.localPosition.ToString());
    c.transform.localPosition = new Vector3(i * 10, 0, 0);
    Debug.Log("After : " + c.transform.localPosition.ToString());
}

在调试日志中我可以看到(#1 迭代日志):

Before : (-288.1, 0.0, 1559.4)
After : (0.0, 0.0, 0.0)

当我进入游戏时,这里是第一个预制件的位置:288.11、298.11、308.11 等等。所以i * 10 起作用了……

如果我在游戏运行时从编辑器手动将 x 设置为 0,它会转到我希望它转到的位置 = 0 位置。

我只想让我动态生成的预制件转到(i * 10, 0, 0) 位置,而不是现在的位置 (( (288.11 + i) * 10, 0, 0))

我希望他们都去x位置0102030等等。

我所说的位置 (0,0,0) 是相对于父级的“左上角”。

这是父配置的截图:

这是我的预制件:

当我手动将 (0,0,0) 设置为其位置时,我希望将第一个元素定位在此处:

我错过了什么?

【问题讨论】:

  • 我认为您应该在 o.transform.position 而不是 Vector3.zero 实例化您的对象。实例化是在世界空间中完成的,即使您指定了父级。
  • 还有一点无关紧要的注释,但是你为什么要以浮点数递增。
  • 他在他的 Vector3 中使用i,它只接受浮点值。我假设这是为了避免强制转换。
  • 转换常量有什么性能提升吗?他仍然需要明确地投射一些东西。
  • 只要你可以避免强制转换,性能总会有小幅提升......但他仍在他的 for 循环中使用强制转换(尽管不需要)......(float)1.0.. 可以轻松地写1.0f(末尾的 f 不是演员表)。

标签: unity3d


【解决方案1】:

好的,感谢您的澄清,我试图保持您的代码完整并注释了注释。这应该将预制件固定到它的相对锚定元素上。

public Transform t; //parent
public GameObject prefabCell;

for (float i = 0; i < 10; i += (float)1.0)
{
    GameObject c = Instantiate(prefabCell, Vector3.zero, Quaternion.identity);
    // Removed the parent parameter and factored it out here.
    // The second parameter forces the worldpos to false
    c.transform.SetParent(t, false); 
    c.transform.localScale = new Vector3(1, 1, 1);
    Debug.Log("Before : " + c.transform.localPosition.ToString());
    // Use anchored position when you manipulate UI elements,
    // the position property is counter-intuitive for canvas.
    c.GetComponent<RectTransform>().anchoredPosition = new Vector3(i * 10, 0, 0);
    Debug.Log("After : " + c.transform.localPosition.ToString());
}

【讨论】:

  • 我希望定位是相对的 = 在父级中,(0,0,0) = 左上 进入 父级
  • 中间不是父母的 (0,0,0) 吗?
  • 我认为您的脚本完全符合您的要求,但也许您对世界单位感到困惑?
  • 如果您在编辑器中手动设置 x 位置,则与设置对象 transform.position.x 属性相同。尝试从 localPosition 切换到普通位置,看看它是否有效。
  • 布兰登在我认为的正确轨道上。如果从逻辑上讲您想在相对空间中工作,请使用 localPosition。但作为一个注释,我假设我已经正确阅读了这个问题:( (288.11 + (i * 10), 0, 0) in world space = (i * 10, 0, 0) in relative parent space。
猜你喜欢
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2020-01-03
  • 2016-06-24
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多