- Home /
Bullet Prefab not instantiating
var BulletPrefab:GameObject;
var force : float = 2000;
function OnGUI()
{
if (GUI.Button(Rect(250,350,75,75),""))
{
var bullet = Instantiate(BulletPrefab,
GameObject.Find("Player").transform.position,
GameObject.Find("Player").transform.rotation);
bullet.rigidbody.AddForce(bullet.transform.forward * force);
}
}
I created a button that's supposed to instantiate and give a forward force to a bullet game object - but whenever I press it, the game object appears in the inspector but not actually on the game screen, can anybody tell me how to fix it?
Is this a 2D game? Are you sure the bullet isn't just embedded within your Player, so you can't see it? Because that's currently where it's being instantiated...
Also, you should be doing the GameObject.Find() in your Start() function once, ins$$anonymous$$d of calling it each time your spawn a bullet, or else you'll get quite bad performance. Just define a player variable and assigned it in Start() with player = GetComponent.Find("Player"). Then you can use player.transform.position anywhere in your script to get the current position of the player, for example.
Spawning the bullet inside another collider could make the physics go crazy and throw the bullet far away. If that is the case either offset the position with somthing like player.transform.forward, or tell it to ignore the players collider: http://docs.unity3d.com/Documentation/ScriptReference/Physics.IgnoreCollision.html
Answer by Yuneza · Feb 05, 2015 at 07:18 AM
Add the Rigid Body and uncheck use gravity in it, it will work. I did the same in my game forgot to add the Rigidbosy