Hey guys, I want to generate a delay to reload the weapon.
For exemple, when the player press “r” the gun reload but have a delay time, I tryied to make it but its gone wrong, i used yield, but it don’t work. Can someone help me ? Don’t need be with yield.
Here my script:
using System.Linq;
using System.Text;
using UnityEngine;
public class Laucher : MonoBehaviour
{
public Rigidbody projectile;
public float reloadDelay = 10;
public float speed = 20;
public int bullet = 6;
public int reload = 40;
public float reloadTime;
private bool canshoot = true;
private bool recarrega = false;
private int reloadnum;
private GUIText balas ;
private GUIText cargas;
public void Update()
{
Debug.Log(reload);
if (canshoot)
{
reloadnum = 6 - bullet;
if (Input.GetButtonDown("Fire1"))
{
Rigidbody instantiatedProjectile = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed));
Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
if (instantiatedProjectile)
{
bullet--;
if (bullet <= 0)
{
bullet = 0;
canshoot = false;
reloadnum = 6;
}
}
}
}
if (Input.GetKeyDown("r") && reload > 0)
{
reload -= reloadnum;
bullet += reloadnum;
canshoot = true;
recarrega = false;
}
if (reloadnum < 0)
{
reloadnum = 0;
}
else if (Input.GetKeyDown("r") && reload < 6 && reload > 0)
{
reloadnum = reload - bullet;
}
}
/*public IEnumerator recarregar()
{
if (recarrega == true)
{
yield return new WaitForSeconds(5);
reload -= reloadnum;
bullet += reloadnum;
canshoot = true;
recarrega = false;
}
*/
}
I can't answer your question, but to help others. Can you clarify what you mean by "but it wont work" and "gone wrong". Just try to explain exactly what isn't working, what were you expecting to happen exactly and what is happening instead. If this isn't the case, state any errors you are getting.
– timskYou cannot use Yield the way you do. You cannot yield in Void Update Use a custom function. Something like so: if(Input.GetKeyDown("r")){ Reload(); } Void Reload(){ yield WaitForSeconds(3); //Continue here. }
– anon28105559Ah... it makes sense now, i shouldve been able to help :D. if you use yield in Update(). Your telling unity to wait every frame ;)
– timsk