首页 > 解决方案 > 获取父对象的坐标

问题描述

我怎样才能获得父对象的坐标,以便它们分别寻址它们的父对象。也就是说,有一个预制的“Flag”,舞台上有3个这样的对象。当他们点击它们时,他们会创建另一个对象而不是自己。那么问题是什么。它是关于获取创建它的父对象的坐标。

/我知道,我写了废话和粥……

应要求提供代码:

public GameObject CreatingBuildingDeleting_FlagObject;

public GameObject CreatingBuilding_Barrack_FlagObject;
public GameObject CreatingBuilding_Tent_FlagObject;

float yPosition = 0.3f;
float Z_index = 5;

public void Build_Barrack()
{
    Replace(CreatingBuildingDeleting_FlagObject, CreatingBuilding_Barrack_FlagObject);

}
public void Build_Tent()
{
    Instantiate(CreatingBuilding_Tent_FlagObject);
    CreatingBuilding_Tent_FlagObject.transform.position = new Vector3(CreatingBuildingDeleting_FlagObject.transform.parent.position.x, yPosition, Z_index);
    Destroy(CreatingBuildingDeleting_FlagObject);
}

void Replace(GameObject ReplaceObject1, GameObject ReplaceObject2)
{
    Instantiate(ReplaceObject2, ReplaceObject2.transform.position, Quaternion.identity);
    Destroy(ReplaceObject1);
}

这就是在世界中创建对象的方式

舞台上的预制件是什么样的,我想从什么创建其他对象: 这就是在世界中创建对象的方式

标签: unity3d

解决方案


更新

实际上,现在仔细查看您的代码后,我认为您实际上想要做的就是

var position = new Vector3(CreatingBuildingDeleting_FlagObject.transform.position.x, yPosition, Z_index);
Instantiate(CreatingBuilding_Tent_FlagObject, position, Quaternion.idendity);
Destroy(CreatingBuildingDeleting_FlagObject);

场景中的实例没有任何关于它们从哪个原始模板克隆的参考/信息。

-> 您必须自己存储和管理它!

例如,您可以在要克隆的原始对象上使用专用组件

public class CloneInformation : MonoBehaviour
{
    // For storing the reference from where you have been cloned
    private CloneInformation _origin;
    // For public read-only acccess
    public CloneInformation Origin => _origin;

    // Optional you can even in the other direction also store direct children cloned from this object 
    private readonly HashSet<CloneInformation> clones = new HashSet<CloneInformation>(); 

    public void Initialize (CloneInformation origin)
    {
        _origin = origin;
        origin.clones.Add(this);
    }

    private void OnDestroy ()
    {
        if(_origin)
        {
            _origin.clones.Remove(this);
        }
    }   
}

然后每当你克隆这样一个对象时,例如

var originInformation = objectToClone.GetComponent<CloneInformation>();
var clonedInformation = Instantiate (originalInformation);
clonedInformation.Initialize(originalInformation);

这样,您现在可以使用例如获取原点位置

var originPosition = someCloneInformation.Origin.transform.position;

甚至可以使用

CloneInformation someClone;
var position = Vector3.zero;

CloneInformation current = someClone.Origin;
while(current)
{
    position = current.transform.position;

    current = current.Origin;
}

推荐阅读