I’m fairly new with OnMouseDrag and Coroutines in general.
What I want to accomplish:
I currently have movement setup on mouse drag. You drag the character back and forth across the screen. I want the character to be shooting while you are dragging.
Issue I am having:
It seems that OnMouseDrag fires a ridiculous amount of times. I have a BulletFire script that is being called from OnMouseDrag, and it is fireing multiple times per second. This results in wayyyy to many bullets being shot.
What I tried:
I’ve tried calling a coroutine from my OnMouseDrag method, but that routine gets called so many times, its actually doing nothing but delaying the initial shot.
So basically here i’m trying to call my shoot method while the mouse button is held down, but I want to be able to have a .5 second or 1 second delay in between calls. Any idea what I am doing wrong?
So, you’ll want to track whether a bullet has been fired in the past half-second. Just set a bool to false, set it true when you fire, and set it back to false in the coroutine. Test that bool to decide whether to fire.
private bool RecentShot = false;
IEnumerator wait()
{
yield return new WaitForSeconds (0.5f);
RecentShot = false;
}
void OnMouseDrag()
{
// Do your stuff
if (!RecentShot)
{
RecentShot = true;
callFireBullet ();
StartCoroutine (wait ());
}
}
I believe what you want to do is just use a while loop! That way it calls it again when it’s done! Also make a new variable and while to check for it and when MouseDown set it to true and on MouseUp make it false!
ok, I fixed up my code for it to work, monodevelop compiles it. then Unity gives me an error.
Assets/dimensionswitcher.cs(6,20): error CS1519: Unexpected symbol `=’ in class, struct, or interface member declaration
this is my new code:
using UnityEngine;
using System.Collections;
public class dimensionswitcher : MonoBehaviour {
bool dimension1 = 0;
dimension1 = true
bool dimension2 = 1;
dimension2 = true
void Update () {
call waitswitch
StartCoroutine (waitswitch());
if dimension1 = true {
if dimension2 = true {`
if (Input.GetKeyDown ("z"))
transform.position = new Vector3 (transform.position.x, transform.position.y, dimension1);
if (Input.GetKeyDown ("x"))
transform.position = new Vector3 (transform.position.x, transform.position.y, dimension2);
}
}
}
}
IEnumerator waitswitch(){
dimension1 = false
dimension2 = false
yield return new WaitForSeconds (3.0f);
dimension1 = true
dimension2 = true
}