Reputation: 105
I am creating a reload script for my PlayerController. I am following Brackey's guide: https://www.youtube.com/watch?v=kAx5g9V5bcM . His method uses IEnumerators and WaitForSeconds to add reload time. Putting it basically, I am logging "reloading" before the yield, and logging "reloaded" after the yield. But, I get "reloading" and "reloaded" at the same time.
I've tried increasing reloading time, in case the time was too short, but nothing has worked.
Here is the inside of my class. I am getting no errors.
public float speed;
private Rigidbody2D rb;
private Vector2 moveVelocity;
public GameObject bullet;
public GameObject shootPoint;
//public float ammo = 6;
//[HideInInspector] public bool reloading = false;
//[SerializeField] private float reloadTime = 3;
//private float reloadState;
public int maxAmmo = 10;
private int currentAmmo;
public float reloadTime = 100f;
private bool isReloading = false;
public float health = 50f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
health = 50;
currentAmmo = maxAmmo;
}
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * speed;
if (isReloading) {
return;
}
if (currentAmmo <= 0) {
StartCoroutine(Reload());
return;
}
if (Input.GetButtonUp("Shoot")) {
Instantiate(bullet, shootPoint.transform.position, Quaternion.identity);
currentAmmo--;
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
void OnTriggerEnter2D(Collider2D other) {
if(other.gameObject.tag == "Bullet") {
health--;
//Debug.Log("Player 1 Health: " + health);
Destroy(other.gameObject);
}
}
IEnumerator Reload()
{
Debug.Log("reloading");
isReloading = true;
yield return new WaitForSeconds(reloadTime);
currentAmmo = maxAmmo;
isReloading = false;
Debug.Log("reloaded");
}
As I said, I am not getting any errors. I am expecting me to not be able to shoot for one second, but I can shoot and reloading does not take one second.
Upvotes: 1
Views: 567
Reputation: 90872
You have declared
public float reloadTime = 100f;
a public
field gets automatically serialized ("stored") by the Unity Inspector.
My guess would be that at first you declared it like
public float reloadTime;
so the Unity Inspector stored it with the default value 0
. Then later you tried to increase that value from within the script.
Any later changes to the initial value within the script won't have any effect. The Unity Inspector will allways overwrite the value with the serialized one.
In order to change your value from now on you always either have to make it using the Inspector, make the field not serialized (e.g. by making it private
) or set it in the Awake
or Start
method which again overwrites the Inspector value.
Upvotes: 2