1

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. So it looks like this:

enter image description here

Spawner2 has a script with the following method, which is called at the start of the game. 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.

So I tried to debug. I pulled Spawner2 out of its parent and see the location (which is 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.

Is it because of my prefab? What is the problem and how can I fix it?

Marc2001
  • 281
  • 1
  • 3
  • 12
  • What happens if you use transform.localPosition instead? – Sean Carey Jan 05 '19 at 04:39
  • @CareyOn If I use transform.localPosition, it instantiates the object a couple of units ahead on the X axis – Marc2001 Jan 05 '19 at 04:50
  • If the local position of Spawner2 has Y=1 your pivot points might not be centered on your spawnedRoom and that's why it seems to spawn at the wrong position (1 unit too high on the y-axis). – PlantProgrammer Jan 05 '19 at 07:46
  • @Marc2001 `Instantiate(..., transform.position, ...);` spawned the game object on the spawner position that code runs on it. Do you want to spawn the game object on the one of this spawners? – Ehsan Mohammadi Jan 05 '19 at 09:33
  • @EhsanMohammadi I want it to spawn at Spawner2. – Marc2001 Jan 05 '19 at 10:49

2 Answers2

1

Use this overloaded method instead:

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

and pass the Spawner2 parent transform as the last parameter. Now new object should be positioned in the same place as the 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);
}
Dave
  • 2,684
  • 2
  • 21
  • 38
1

EDIT: I started a new project and did the exact same thing except now, the prefab position is set to 0 on all axis. 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. It's position + prefab position.

Marc2001
  • 281
  • 1
  • 3
  • 12