UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Hitscan Weapon system"
using UnityEngine; public class HitscanWeapon : MonoBehaviour { public Camera fpsCamera; public float range = 100f; public float damage = 25f; public LayerMask layerMask; // Update is called once per frame void Update() { if (Input.GetButtonDown("Fire1")) { Shoot(); } } void Shoot() { RaycastHit hit; if (Physics.Raycast(fpsCamera.transform.position, fpsCamera.transform.forward, out hit, range, layerMask)) { Debug.Log(hit.transform.name); // Apply damage to the target if it has a Health component Health targetHealth = hit.transform.GetComponent<Health>(); if (targetHealth != null) { targetHealth.TakeDamage(damage); } } } } [System.Serializable] public class Health : MonoBehaviour { public float maxHealth = 100f; private float currentHealth; void Start() { currentHealth = maxHealth; } public void TakeDamage(float damageAmount) { currentHealth -= damageAmount; if (currentHealth <= 0) { Die(); } } void Die() { // Handle death logic, e.g. destroy the object or play an animation Destroy(gameObject); } }