- Home /
My instantiated object won't appear at the parent position
So I have a "home location" for the objects I want to instantiate. In the parent script, I have the below code:
Instantiate(ant,transform.position,Quaternion.identity);
When I write transform.position to the console it's correctly returning the co-ordinates, e.g. -77.5,22.3,0.0 . But the child object always spawns in the middle of the screen. Why isn't it spawning correctly at the given co-ordinates?
Answer by MGUELfig189 · Sep 04, 2021 at 06:21 PM
@MrTeddyBearr as the instances? with a lightning launch or spawned in front of the player, say more details in these cases, if it is with a lightning launch, use this
Vector3 nin= hit.collider.transform.position + hit.normal;
Instantiate (ant, nin, Quaternion.identity);
Answer by MrTeddyBearr · Sep 04, 2021 at 06:42 PM
Sorry @MGUELfig189 let me expand a bit. So I'm first spawning a series of prefabs using the below:
//Get the boundaries
Vector2 screenDimenions = new Vector2(Screen.width,Screen.height);
Camera mainCam = Camera.main;
Vector2 worldBoundaries = mainCam.ScreenToWorldPoint(screenDimenions);
//Take off 20% to give a buffer
float x = worldBoundaries.x * 0.8f;
float y = worldBoundaries.y * 0.8f;
//Spawn starter colonies
spawnColonies(x,y);
Then:
private void spawnColonies(float x, float y){
for(int i = 0; i < colonyCount; i++){
Vector2 colonyPos = new Vector2(Random.Range(-x,x),Random.Range(-y,y));
Instantiate(colonyPrefab,colonyPos,Quaternion.identity);
}
}
Now, the colony prefab has a script attached to it. What I want to do is spawn the ant prefabs at the colony position, so then within the colony script I'm calling the below code:
public void spawnAnts(GameObject ant){
for(int i = 0; i < colony_size; i++){
Instantiate(ant,transform.position,Quaternion.identity);
}
}
Now I expected the ants to spawn at the same position as the colony, but for some reason they just appear in the middle of the screen.
@MrTeddyBearr Oh I got it, but the colony is not randomly instantiated. it is generated only at one point, right?
@MrTeddyBearr Instantiate(ant, new Vector3(0, 0, 0), Quaternion.identity);
in 0 put the coordinates where you want to instantiate the ants
Unfortunately the colonies are randomly generated throughout the scene, so I need to be able to generate the ants at the same co-ordinates (which will change)