Unity3d transform.position未返回正确的值



我正在研究的一些背景:基本上我有一个立方体模型,它将用于生成一些地形结构。所有这些游戏对象都是在Runtime上通过以下操作创建的:

float yPos = 0f;
float scale = 0.5f;
var robot = GameObject.Instantiate(grassTile) as GameObject;
robot.transform.position = new Vector3(0, yPos, 0);
robot.transform.localScale = new Vector3(scale, scale, scale);
robot.transform.rotation = Quaternion.Euler(-90, 0, 0);
width = robot.GetComponent<Renderer>().bounds.size.z;
for(int i=0;i<5;i++){
yPos += width;
robot = GameObject.Instantiate(grassTile) as GameObject;
robot.transform.position = new Vector3(0, yPos, 0);
robot.transform.localScale = new Vector3(scale, scale, scale);
robot.transform.rotation = Quaternion.Euler(-90, 0, 0);
//attach the script
robot.AddComponent<CubeBehavior>();
}

CubeBehavior.cs:的内部内容

void Start () {
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0) {
Debug.Log(transform.position);
}
}

发生的事情是,无论我触摸哪个立方体,它都会返回最后一个立方体位置。请就这些问题告诉我。提前感谢

您没有检测哪个多维数据集被触摸的代码。

Input.touches只是告诉您当前在屏幕上检测到了多少触摸。

要检测触摸,您需要做更多的工作。一种可能的解决方案是实现触摸事件处理程序。受文档启发的示例:

public class CubeBehaviour : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
//Detect current clicks on the GameObject (the one with the script attached)
public void OnPointerDown(PointerEventData pointerEventData)
{
//Output the name of the GameObject that is being clicked
Debug.Log(name + " click down at position " + transform.position);
}
//Detect if clicks are no longer registering
public void OnPointerUp(PointerEventData pointerEventData)
{
Debug.Log(name + "No longer being clicked");
}
}

这将需要在场景中的某个位置使用EventSystem。可能,你还需要在立方体上触发对撞机,不确定

最新更新