I want to spawn a prefab at 0, 18, 0 when the script starts. I have this and it spawns at 0, 0, 0 Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public GameObject Prefab1; void Start(){ Instantiate(Prefab1, new Vector3(0f,10f,0f), Quaternion.identity); transform.Translate(0, 18, 0); } }
The following code (line 10) is setting the position of the Spawner script parent object as opposed to the instantiated prefab Code (csharp): transform.Translate(0, 18, 0); Try this... Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public GameObject Prefab1; // void Start(){ Instantiate(Prefab1, new Vector3(0f,18f,0f), Quaternion.identity); } }
Does your Prefab contain a script that handles its own position and potentially sets it to (0,0,0)? The code Vectorbox showed should work for spawning it at 18f height, so if it does not end up there, something else changed the position.
As Yoreki says, the revised script I posted does return the required result with a 'standard' prefab. If you can't identify the issue, post a download link to your prefab and I'll take a look. Unity Manual Instantiate Object
The transform put by itself refers to the spawner object. While you want to change the ownership of the spawned object then: Code (CSharp): using UnityEngine; public class Spawner : MonoBehaviour { public GameObject Prefab1; void Start() { GameObject go = Instantiate(Prefab1, new Vector3(0f, 10f, 0f), Quaternion.identity); go.transform.Translate(0, 8, 0); } }
What ciorbyn (and also Vectorbox in his first reply) said about transform.Translate moving the current object is of course true, but.. based on what OP wrote, that's not what he / she asked for. OP asked how to spawn something at 18f height. Where something spawns is handled with the second parameter of Instantiate(). Why would we spawn it at 10 and move it up 8, when we can spawn it at 18? Am i missing something?
Yup, @unity_bnFYkXS0r3Iu4w is still at the crowbar-coding stage, getting their bearings: "It doesn't matter how you get there - as long as you do get there" That being said, you'd be surprised how many seasoned programmers unthinkingly spawn-then-position rather than spawn-at-position. I dimly seem to even remember some Unity-backed tutorials that do this.
Yes, the correct code is: Code (CSharp): void Start(){ Instantiate(Prefab1, new Vector3(0f,18f,0f), Quaternion.identity); } But as it didn't work and the rest is unknown, I limited myself to literally correcting the original code. The fact that the instance at (0,18,0) didn't work for me also remains a mystery.