- Home /
How do I make a script that will allow my character to shoot projectiles?
How do I make a script that will allow my character to shoot projectiles? I tried to make it of the tutorial but there are no tutorials on this in my native language.
Answer by Acdia · Aug 10, 2020 at 07:27 AM
To make it easier you could at first create an empty gameobject under your player and move it in front of the player. (You could also use layers to avoid collisions with the player, but this is just a simple solution) To this gameobject you can attach a script in which you create a public GameObject, for example named bullet. In the inspector you can drag in a prefab of a bullet (For example a small sphere with a rigidbody). In the script you then check in Update()
if (Input.GetButtonDown("Fire1"))
{
}
Fire1 is normally set to the left mouse button. In the open space you then instantiate the bullet and safe it to a variable:
GameObject myBullet = Instantiate(bullet, transform.position, transform.rotation);
You now get the Rigidbody of the bullet...
Rigidbody rb = myBullet.GetComponent<Rigidbody>();
You can optionally check if there is a Rigidbody after this
if(rb == null) return;
But this isn't that important and now you apply a force
rb.AddForce(Vector3.forward * 200f, ForceMode.VelocityChange);
VelocityChange means that the bullet is speed up instantly. Now every time you click the left mouse button a bullet should be shot. One thing to improve the performance is to delete the bullets after a while. You can attach this line to Shooting Script:
GameObject.Destroy(myBullet, 20f);
This would destroy the bullet after 20 seconds.
Your answer
![](https://koobas.hobune.stream/wayback/20220613005314im_/https://answers.unity.com/themes/thub/images/avi.jpg)