DEV Community

Sarvesh Kesharwani
Sarvesh Kesharwani

Posted on

C# code to create a bullet and shoot it in Unity

using UnityEngine;

public class ShootBullet : MonoBehaviour
{
    // Reference to the bullet prefab
    public GameObject bulletPrefab;

    // Speed of the bullet
    public float bulletSpeed = 10.0f;

    // Update is called once per frame
    void Update()
    {
        // Check if the player pressed the fire button (left mouse button)
        if (Input.GetButtonDown("Fire1"))
        {
            // Create a new bullet instance
            GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);

            // Get the rigidbody component of the bullet
            Rigidbody rb = bullet.GetComponent<Rigidbody>();

            // Add force to the bullet to shoot it forward
            rb.AddForce(transform.forward * bulletSpeed, ForceMode.Impulse);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)