简体   繁体   English

Unity2D-transform.position不等于现实世界的位置

[英]Unity2D - transform.position is not equal to the real world position

Okay, the title may be confusing cause I don't how to know put it. 好的,标题可能令人困惑,因为我不知道该怎么说。

My case: I have a 2d sprite with 4 child objects, each one place around the sprite as a perimeter. 我的情况是:我有一个带有4个子对象的2D子画面,每个子画面围绕该子画面一个周边。 So it looks like this: 所以看起来像这样:

在此处输入图片说明

Spawner2 has a script with the following method, which is called at the start of the game. Spawner2具有使用以下方法的脚本,该脚本在游戏开始时被调用。 Inside the script, I instantiated a new prefab: 在脚本中,我实例化了一个新的预制件:

public void GenerateBox(int count)
{
    ...
    GameObject spawnedRoom = Instantiate(possibleRooms[chosen], transform.position, Quaterion.identity);
}

But this instantiates the object at Spawner1's location. 但这会在Spawner1的位置实例化该对象。

So I tried to debug. 所以我尝试调试。 I pulled Spawner2 out of its parent and see the location (which is X: 1.0062, Y: -0.0038). 我从其父级中拉出Spawner2并查看了位置(X:1.0062,Y:-0.0038)。 I put it back inside the 2d sprite and when I debug.log it's position, it gives me X: 0, Y: 1, Z: -9.8. 我把它放回2d精灵中,当我调试它的位置时,它给了我X:0,Y:1,Z:-9.8。

Is it because of my prefab? 是因为我的预制件吗? What is the problem and how can I fix it? 有什么问题,我该如何解决?

Use this overloaded method instead: 请使用此重载方法:

Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

and pass the Spawner2 parent transform as the last parameter. 并将Spawner2父转换作为最后一个参数传递。 Now new object should be positioned in the same place as the Spawner2. 现在,新对象应与Spawner2放在同一位置。 In the end your function should look like this: 最后,您的函数应如下所示:

public void GenerateBox(int count)
{
    ...
    GameObject spawnedRoom = Instantiate(possibleRooms[chosen], transform.position, Quaterion.identity, transform.parent);
}

EDIT: I started a new project and did the exact same thing except now, the prefab position is set to 0 on all axis. 编辑:我开始了一个新项目,并做了完全相同的事情,除了现在,预制位置在所有轴上都设置为0。 Everything works fine now. 现在一切正常。 I'm guessing this happens because of the prefab's position. 我猜这是由于预制件的位置而发生的。 For example, you instantiate the prefab in the script at (0, 0, 0) world position and the prefab position is (2, 1, 0), then the prefab will spawn at (2, 1, 0) world position. 例如,您在脚本中的世界位置(0,0,0)处实例化预制件,并且预制位置为(2,1,0),然后该预制件将在世界位置(2,1,0)生成。 It's position + prefab position . 它是位置+预制位置

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

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