- Home /
Instatiate prefab at another prefab issue
I have created a simple script that instatiates a coconut prefab at the location of a tree prefab. However I'm running into a major issue. The coconut only instatiates at my palm tree pivot point. Which is at the bottom of the trunk. I have searched up and down google for an answer, like how to make my coconut spawn higher up than the pivot point or father out from the trunk but I have found nothing. Here is the code:
using UnityEngine;
using System.Collections;
public class CoconutGen : MonoBehaviour {
public GameObject spawnThis;
// Use this for initialization
void Start () {
Instantiate(spawnThis, transform.position, transform.rotation);
}
// Update is called once per frame
void Update () {
}
}
Answer by aldonaletto · Sep 14, 2013 at 10:11 PM
The second parameter you pass to Instantiate is the position: just add an offset to it - like this:
...
public GameObject spawnThis;
public Vector3 offset = new Vector3(0, 2, 0); // offset relative to the pivot
// Use this for initialization
void Start () {
Instantiate(spawnThis, transform.position + offset, transform.rotation);
}
...
This offset sets the position 2 units above the pivot.
If you want to create several coconuts, add some random offset too:
Instantiate(spawnThis, transform.position + offset + Random.insideUnitSphere, transform.rotation);
You sir are a genius. I was trying to do something like that, except I was going about it all the wrong way. Thank you for the help.