unity3d - 获取父对象的坐标
问题描述
我怎样才能获得父对象的坐标,以便它们分别寻址它们的父对象。也就是说,有一个预制的“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);
}
解决方案
更新
实际上,现在仔细查看您的代码后,我认为您实际上想要做的就是
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;
}
推荐阅读
- c - C - 将字符添加到字符串的开头
- php - 如何使用正则表达式获取特定字符串?
- javascript - 如何在 iframe 元素中获取动态添加的 body 元素
- oop - 如何在python的OOP中的类中使用try和except
- jenkins - 何时使用全局/本地 CodeceptJS 安装?
- python - 日期和时间列具有混合格式
- excel-formula - 仅当值第一次出现时才计算匹配多个条件的行
- javascript - 如何将一个mongodb请求的结果同步传入下一个请求的值?
- php - 我写了一个 Wordpress 插件简码,当我尝试使用该简码更新页面时,它给了我一个 Header Allready sent 错误
- python - 用python删除文件中的第一个x字符