- Home /
Question by
Patpig10 · Mar 13 at 01:28 PM ·
gun script
How to add a Gun Reload feature to my script
using System.Collections; using System.Collections.Generic; using UnityEngine;
namespace CodeMonkey.HealthSystemCM {
public class BulletController : MonoBehaviour
{
public float speed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
Destroy(gameObject, 2);
}
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out EnemyHealth Enemy))
{
Enemy.Damage();
Destroy(gameObject);
}
}
}
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
namespace CodeMonkey.HealthSystemCM {
public class GunController : MonoBehaviour
{
public bool isFiring;
public BulletController bullet;
public float bulletSpeed;
public float timeBetweenShots;
private float shotCounter;
public Transform firePoint;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (isFiring)
{
shotCounter -= Time.deltaTime;
if (shotCounter <= 0)
{
shotCounter = timeBetweenShots;
BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController;
newBullet.speed = bulletSpeed;
}
}
else
{
shotCounter = 0;
}
}
}
}
Comment
Best Answer
Answer by rh_galaxy · Mar 13 at 01:54 PM
Maybe like this:
private bool isFiring = false;
private bool isReloading = false;
private int shotsInSequense = 0;
private float shotTimeCounter = 0.0f;
void Update()
{
shotTimeCounter += Time.deltaTime;
if (isReloading)
{
if(shotTimeCounter > 4.0f) //reload time 4S
{
isReloading = false;
shotTimeCounter = 0.0f;
shotsInSequense = 0;
}
} else {
if (isFiring)
{
if (shotTimeCounter > timeBetweenShots)
{
shotsInSequense++;
if(shotsInSequense>6) isReloading = true; //6 shots then reload
else {
shotTimeCounter = 0.0f;
BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController;
newBullet.speed = bulletSpeed;
}
}
}
}
}
Update: added shotsInSequense = 0;
Your answer
