- Home /
Creating more objects with code.
I am trying to set up a script that will let me create new projectiles for my catapult to fire.
Eventually this will be limited to one at a time and will let the player choose between three different materials with different weights. However, I do not need to worry about this just yet.
When I press the right button to trigger the script, I can see the scroll bar in the Hierarchy moving and getting smaller, so there are obviously new entries being added. The big question for me is, why can't I see these new objects? I believe I am putting them on a visible part of the screen for my static camera to view. Am I missing a vital component?
My code is as follows:
var projectile : GameObject; var rb : Rigidbody; var mr : MeshRenderer; var bc : BoxCollider;
function Update(){
if(Input.GetKeyDown (KeyCode.Q)) { projectile = new GameObject ("Projectile"); projectile.tag = "projectile";
bc = projectile.AddComponent("BoxCollider"); projectile.collider.center = Vector3.zero;
mr = projectile.AddComponent("MeshRenderer");
rb = projectile.AddComponent("RigidBody"); projectile.rigidbody.isKinematic = true;
projectile.transform.position = Vector3(0,1,0); } }
As soon as you press the key, pause the game and zoom into one of these objects (in the Editor) to see if all components are O$$anonymous$$ and if they didn´t just fall down after you created them (because of their RigidBody).
Thanks I just did this. The objects are staying put because they are kinematic. The problem is all I can see is the green frame around them and no actual texture.
Answer by hotemup · Jan 05, 2012 at 07:48 PM
Your GameObject has no mesh. The mesh tells the computer what the GameObject is shaped like and such. So you are making a GameObject, but the computer doesn't know what you want it shaped like so it cannot render it, and also cannot figure out where the bounds of the collider should be. You would have to add a Mesh Filter and a mesh to that mesh filter for the computer to figure it out.
Also, instead of reconstructing the exact same object each time, it is easier to make a prefab in the inspector and use GameObject.Instantiate.
the object still shows up blank, even after defining the mesh filter in the inspector view of the script under the gameObject it is attached to.
Answer by Dreamside · Jan 18, 2012 at 09:16 AM
Probably your mesh renderer does not have any material attached and also does not have a mesh filter.You should check these
Your answer
Follow this Question
Related Questions
AddComponent() causes a "trying to create a MonoBehaviour using the 'new' keyword" warning 2 Answers
Weird Glitch When Instantiating a Game Object 1 Answer
Cannoot change variable of Component after Instantiating GameObject 0 Answers
Instantiating a Rigidbody instead of a GameObject 1 Answer
Instantiate does not return 3 Answers