Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c sharp gun shooting

using UnityEngine;

public class Gun : MonoBehaviour
{
    public float damage = 10f;
    public float range = 100f;
    public float impactForce = 30f;

    public Camera fpsCam;


    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1")) {

            Shoot();
        }
    }

    void Shoot () {

        RaycastHit hit;
        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range)) {

            Target target = hit.transform.GetComponent<Target>();

            if (hit.rigidbody != null) {

                hit.rigidbody.AddForce(-hit.normal * impactForce);
            
            }

            if (target != null) {

                target.TakeDamage(damage);
            
            }
        
        }  
    }
}


health


using UnityEngine;

public class Gun : MonoBehaviour
{
    public float damage = 10f;
    public float range = 100f;
    public float impactForce = 30f;

    public Camera fpsCam;


    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1")) {

            Shoot();
        }
    }

    void Shoot () {

        RaycastHit hit;
        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range)) {

            Target target = hit.transform.GetComponent<Target>();

            if (hit.rigidbody != null) {

                hit.rigidbody.AddForce(-hit.normal * impactForce);
            
            }

            if (target != null) {

                target.TakeDamage(damage);
            
            }
        
        }  
    }
}
 
PREVIOUS NEXT
Tagged: #sharp #gun #shooting
ADD COMMENT
Topic
Name
6+9 =