I’ve created this script attached to a gun. The script fires the gun, and I am working to make the gun deal damage if the bullet hits an enemy. Here is the script
using UnityEngine;
using System.Collections;
public class PlayerGunController : MonoBehaviour
{
public float fireRate = 1;
public GameObject bullet;
public int damage;
public int ammo = 15;
private float nextFire = 1;
void Update ()
{
if(Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Fire();
ammo--;
}
}
void Fire()
{
float range= Mathf.Infinity;
Ray ray= Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, range))
{
bullet.transform.position = hit.point;
if(hit.transform.gameObject.tag == "Enemy")
{
hit.transform.GetComponent<EnemyHealth>().health -= damage;
}
}
}
}
The functionality of this script is simple. There is a block in the level that acts as the bullet. It is assigned as Bullet for this script. When the “fire” button is clicked, the block’s position is changed to the location of the cursor at that moment. If the object the block is touching is tagged as enemy, the enemy takes damage. It works in that sense.
The problem is that is “fire” is pressed multiple times without moving the cursor, the first block hits the enemy, but the second click only hits the position of the previous block, not the enemy.
I was thinking I could just say to destroy the gameobject when it hits something (Don’t know how or where I’ll do that. Haven’t gotten that far yet). The problem with that is there is only one bullet. If I destroy it, that’s it. No more ammo. We can’t have that.
The solution for THAT problem is to use prefabs. So can I edit this script to retain this functionality, but use a prefab of a bullet instead?
Not entirely sure what you mean with the whole "ammo as a number thing." But you explanation of the actual process helped. I don't need a bullet object at all. It's the Raycast that matters. So I just took the whole deal about transforming the position of the bullet out, and eliminated the bullet altogether. Now the ray casts out, hits an object, and checks the tag. If the tag is an enemy, health is taken away from it. End of story. Thanks Habit!
– caleb_bWhat I mean by ammo as a number is that you just have some number that keeps track of how much ammo your gun has. int ammo = 15; // You do this already. Then every time you shoot, you subtract from your ammo. ammo--; // You are doing this already. Then you just check to see if you have ammo before you shoot. Input.GetButton("Fire1") && Time.time > nextFire && ammo > 0 So really, you're already doing it, except for the part where you check to see if they have ammo before they fire the gun.
– HabitablabaOh! I get it! Sorry, I thought I had that function in there Lol I meant to but I forgot it. Thanks again!
– caleb_b