I realize how I can add GameObjects to the scene and add components to them through scripting, but I cannot seem to add a Sphere. I can add Spheres through the GUI by selecting the Sphere in the menu, but I need to do so in a script.
I have tried this:
sBall = new GameObject("New Sphere");
sBall.AddComponent("RigidBody");
sBall.AddComponent("SphereCollider");
The GameObject is added, but it is invisible. I assume this is because there is no mesh assigned to the object. I guess I need to add a sphere mesh, but how?
Also, I’d like to clone an existing object which was added to the scene through the GUI. The object’s name is “Sphere 1”. How do I clone this object in a script?
You can clone an existing object or prefab by calling Instantiate
When creating the game object from scratch, you will also need to add a Renderer to it as well as assigning a mesh and a material to the renderer. It’s much easier to create a prefab containing the object you want to create and use Instantiate.
Thanks, I’m almost there. I’ve created a prefab object named “SphereObj”. I’d like to Instantiate 5 copies of it.
This code does not work. Unknown identifier: “SphereObj”.
Instantiate ("SphereObj", Vector3(0, 0, 0), Quaternion.identity);
How do I reference “SphereObj” so that I can make copies of it?
// spherePrefab then has to be connected in the inspector!
var spherePrefab : GameObject;
Instantiate(spherePrefab, Vector3(0, 0, 0), Quaternion.identity);
This and other concepts are explained in the Scripting Tutorial next to Unity.
It is an excellent starting point for getting to know the scripting side of Unity.