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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay