简体   繁体   English

Unity - 如何获取父游戏对象中心的位置

[英]Unity - How to get location of center of parent gameobject

I've a question about how to get the transform created by the addition of child objects to a parent.我有一个关于如何获得通过将子对象添加到父对象而创建的转换的问题。 It's easier to see what I mean by looking at the picture that follows.通过查看下面的图片更容易理解我的意思。 Tranform .变换 I understand that the world position of the parent is effectively at 0 but how do I get the displayed one?我知道父母的世界位置实际上是 0 但我如何获得显示的位置?

Best Regards此致

Some info, first. 首先,一些信息。 That location is where the Center of that GameObject is. 该位置就是该GameObjectCenter The alternative to having the handles there is at the Pivot , which will put the handles at the same location as Transform.position . 除了在Pivot放置手柄之外,还可以将其放置在与Transform.position相同的位置。 You can toggle between those two handle display modes in the Unity Editor. 您可以在Unity Editor中在这两种手柄显示模式之间切换。

So, you want to find the location of the Center handles. 因此,您想找到Center手柄的位置。 That depends on if the parent has a Renderer or not. 这取决于父级是否具有Renderer

In your situation, where the parent object has no Renderer , you have to go into the children of the gameObject and average their transform positions: 在您的情况下,父对象没有Renderer ,则必须进入gameObject的子对象并平均其变换位置:

Vector3 sumVector = new Vector3(0f,0f,0f);

foreach (Transform child in parentObject.transform)
{          
    sumVector += child.position;        
}

Vector3 groupCenter = sumVector / parentObject.transform.childCount;

If the situation were a little different and the parent gameObject had a Renderer , then it is much easier: 如果情况略有不同,并且父gameObject具有Renderer ,那么它会容易得多:

Vector3 groupCenter = parentObject.getComponent<Renderer>().bounds.center;

I met the same problem.我遇到了同样的问题。 Thanks for the answer of @Ruzihm.感谢@Ruzihm 的回答。 I want to make the center, but don't know whether the object has 'Renderer', so I write recursive function like this to get a center pos of the object.我想制作中心,但不知道对象是否有'Renderer',所以我写了这样的递归函数来获取对象的中心位置。

Vector3 getCenter(Transform obj)
{
    Vector3 center = new Vector3();
    if (obj.GetComponent<Renderer>() != null)
    {
        center = obj.GetComponent<Renderer>().bounds.center;
    }
    else
    {
        foreach (Transform subObj in obj)
        {
            center += getCenter(subObj);
        }
        center /= obj.childCount;
    }
    return center;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM