- Home /
Issue Instantiating prefab in C#
HI There,
I'm trying to instantiate an object using C# to a specific spawn point. I want it to instantiate as a child of the script object as well..
My code so far is as follows:
using UnityEngine; using System.Collections;
public class enemySpawn : MonoBehaviour {
public float spawnTimer;
public float spawnGap;
public GameObject parentGameObject;
public GameObject enemyObject;
public Transform spawnA;
public Transform spawnB;
public Transform spawnC;
public Transform spawnD;
// Use this for initialization
void Start () {
spawnTimer = 0;
spawnGap = 7.0f;
}
// Update is called once per frame
void Update () {
if (spawnTimer > 0)
spawnTimer -= Time.deltaTime;
if(spawnTimer < 0)
spawnTimer = 0;
if(spawnTimer == 0){
spawnTimer = spawnGap;
GameObject go;
go=Instantiate(enemyObject,spawnA.position, spawnA.rotation) as GameObject;
go.transform.parent=transform;
}
}
}
This instantiates an object, but it's instantiating it with a messed up scale. Rather than the objects scale of 0.6, it's giving it '6.25e-05'
Answer by aldonaletto · Nov 10, 2011 at 04:23 PM
When you set the new object's parent, its scale is recalculated to keep the original proportions; if the parent is huge, the object's scale may become very small. If you just need all of these objects to be childed to a common parent, you can have an empty object for this purpose.
Answer by Tyler 10 · Nov 10, 2011 at 06:09 PM
I always have trouble setting the spawned objects position and then parenting it. What I do is instantiate the spawned object at the parent objects position (like you are doing) and then use local position/rotation after I parent it. Like this:
go.transform.parent = transform; go.transform.localPosition = new Vector3(0,0,0); go.transform.localScale = new Vector3(1,1,1); go.transform.localRotation = . . . . ..