Programatically created Prefabs not appearing


Im learning Unity, so please bear with me if my terminology is slightly off.

I have a basic screen with a moveable target, and an avatar. (Both Prefabs, but dragged onto the screen so appear in the hierarchy.)

I have a script attached to the moveable target (That allows it to move based on key presses. In addition, when I press a certain key, the avatar moves to the target then stops. This is achieved by having a move script that is attached to the avatar, and when the move key is pressed, this finds the Game object for the avatar, and then invokes the move script, passing in the location to move to.)

I have duplicated this behaviour, trying to get it so that I can shoot at the target instead of running to it.

The relevent portion of the attach script is;

if (PrefabBullet == null)
  Prefab Bullet = new GameObject("PrefabBullet");

GameObject o = GameObject.FindGameObjectWithTag("Avatar");
//Get the start point of the bullet
var shootPosition = o.transform.position + o.transform/forward * 0.9f;
//Create a Bullet
var bullet = (GameObject)Instantiate(PrefabBullet, shootPos, o.transform.rotation);
bullet.rigidbody.velocity = transform.forward * 3.0f;
//Set to 200 to give me plenty of time to see it
Destroy(bullet, 200.0f);

Yet when the script is triggered, the code goes through but nothing appears on the screen.

So is there an obvious mistake in the above code?

And as a supplemental Question.
Being as I would eventually like to have 2 avatars able to move, is it actually the right thing to do to use FindGameObjectWithTag(“Avatar”), or should I maintain a collection of Avatars seperately, and track the one that is issuing the commands in a different manner?

Your Bullet doesn’t have a Renderer (and therefore also no mesh or anything) attached to it. So while the object is probably being created correctly, you still need to attach a (Mesh)Renderer to actually see it (and probably a collider as well for physics behaviour). Why not just create a regular prefab and use that. If you don’t want to or cannot put in a reference variable, you can always load the prefab via Resources.Load

Your answer helped me pin it down.

I had a prefabbullet in the project pane, so assumed that by Instantiating it I was making a copy of that. What I was actually doing was creating a blank object with the same name. Load.Resource() was the missing step.

Now onwards to making it move :slight_smile: