- Home /
Automatic Cloning on Instantiation
I've been experimenting with Instantiation and GameObjects in code recently. I'm new to Unity, so I don't really know what I'm doing all too well, I've read some of the documentation, however, I've come across a problem.
I have the following code to Instantiate a sphere at the player's current position: using UnityEngine; using System.Collections;
public class MainScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
Vector3 spawnLoc = GameObject.Find("First Person Controller").transform.position;
GameObject bull = (GameObject)Instantiate(GameObject.CreatePrimitive(PrimitiveType.Sphere),spawnLoc,transform.rotation);
bull.AddComponent<Rigidbody>();
}
}
}
This manages to create the object, however, Unity creates the object and places it at position 0,0,0, then clones it at the player's position.
I've tried putting this in the start function also, and it still spawns both. Can somebody highlight my wrongdoing?
Thanks, Manatross.
Answer by robertbu · Dec 15, 2013 at 07:04 PM
CreatePrimitive() creates a game object in the Scene. Instantiate() clones things including game objects. Instantiate() works for prefabs, but it also works for scene items. So you are first creating a game object in the scene, then you are creating a clone at the position of your controller. Instead:
GameObject bull = GameObject.CreatePrimitive(PrimitiveType.Sphere);
bull.transform.position = spawnLoc;
bull.transform.rotation = transform.rotation;
It is a bit strange to move the object to 'spawnLoc' but to take the rotation from the game object this script is attached to. I'd expect both to either use 'First Person Controller' for both, or to use game object this script is attached to for both.
Your answer
![](https://koobas.hobune.stream/wayback/20220613124232im_/https://answers.unity.com/themes/thub/images/avi.jpg)