0

Anyone knows a prettier solution to check if a key has been pressed X amount of times regardless of time instead of keeping track of a variable that counts the clicks?

I don't want to do this:

if (leftmousebuttonclicked && count == 0){
count++;
//logic
}
if (leftmousebuttonclicked && count == 2){
//logic
count = 0;
}

any cleaner solution than that?

5
  • 3
    you will never enter the else if Feb 7, 2020 at 12:14
  • @TomislavBaljint Haha yeah oops.
    – Loafwad
    Feb 7, 2020 at 12:17
  • Does this work for you? docs.unity3d.com/ScriptReference/Event-clickCount.html
    – Ignasi93
    Feb 7, 2020 at 12:25
  • @Ignasi93 well, surely not if they want triple/octa/n-clicks Feb 7, 2020 at 12:27
  • @quetzalcoatl yeah I'd want to register multiple clicks beyond two clicks as well. Which even the way I am doing it now won't let me do that because I have to reset at the second click.
    – Loafwad
    Feb 7, 2020 at 12:36

5 Answers 5

2

Another way is to use modulo.

int count = 0;
int max_allowed = 3;
if(clicked)
    count++;

// A
count = count % max_allowed;
// B

A will output 1 2 3 1 2 3 1 2 3 B will output 1 2 0 1 2 0 1 2 0

Depending on your goal you need to to your logic on A or B.

1
  • 1
    This is excellent this is the best suggestion yet. Will be marked as the answer unless there's a better solution by the end of the day.
    – Loafwad
    Feb 7, 2020 at 13:36
2

Disclaimer: I have no experience in Unity, so YMMV

However, there is an interesting project that attempts to add RX Extensions to Unity.

-> https://github.com/neuecc/UniRx

RX Extensions is a whole topic on its own, but to keep it short, RX changes the way you observe, analyze and react to incoming events. Instead of attaching an event listener with a block of code that will react to the event, events are "collected" or "transformed" into streams that later can be filtered, aggregated, etc.

An example from above-linked GitHub page:

var clickStream = Observable.EveryUpdate()
  .Where(_ => Input.GetMouseButtonDown(0));

clickStream.Buffer(clickStream.Throttle(TimeSpan.FromMilliseconds(250)))
  .Where(xs => xs.Count >= 2)
  .Subscribe(xs => Debug.Log("DoubleClick Detected! Count:" + xs.Count));

clickStream is a stream-of-clicks observed from GetMouseButtonDown (so probably left moune button). Later it is "buffered"/"windowed" over 250milliseconds and filtered to see if there were more than 2 clicks in that timespan. Next, Debug.Log is invoked only if such condition occurs (more than 2 clicks in 250ms).

There is _a lot_ of other operations/possibilities than just Buffer/Throttle and Where

see for example this: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-merge

(side note: merge is useful if you want to react on events from multiple sources: for example, have a bomb explode when user clicks on it, or when network packet arrives, or when disk runs out of space -- 3 sources: clicks(filtered by mouse button, count, and location), network(filtered by packet type), diskevents(..); moerge those three, filter over (bomb has not exploded yet), then add just one event handler, done).

Don't mind that this last link is for javascript, RX extensions are available on many platforms and the overall idea is the same (although availability of tools/methods vary). Personally, I find those diagrams on that site very helpful.

If you are writing an event-based application (which most of the games are, and most of the UIs in general are), then RX can really open a new world of handy tools for you.

However, to be fully honest, there is a cost to that: if you never used RX before, it may be a bit hard to get your head around it at the first time you try to use RX. That's because RX processes events in a totally different way than you're used to. But then, every new tool requires us to learning a bit about it, so I hope you will find RX useful!

1
//initial value of count
count = 0;
.    
.
.
if(mouseClicked)
{
    //Remove if condition below if you are working with double-click(only remove the condition not Invoke() statement)
    if(count == 0)
       Invoke("resetClickCounter", maxTimeToDetectAnotherClick);

    count++;
    if(count == desiredAmountOfClickCount){
        //your Logic
        count = 0;
    }
}

This is how I write my multi-click counter. If it is only for double clicks I just remove the if condition before Invoke().

9
  • Cleaner for sure. Was hoping for an even cleaner solution.
    – Loafwad
    Feb 7, 2020 at 12:22
  • 6
    count is never 0 so the first if is never true.
    – Everts
    Feb 7, 2020 at 12:28
  • @Everts now it is. Feb 7, 2020 at 12:29
  • I like @Ankit 's solution actually but having to edit the code in the future if I want to go beyond 2 clicks is what is annoying me
    – Loafwad
    Feb 7, 2020 at 12:39
  • No, you don't have to sir, @Loafwad. You just have to remove if(count == 0) if you want to use this for double click. though you can use this as it is. I'm telling you because of reduced complexity. Feb 7, 2020 at 12:40
0

Not prettier but diferent (and only if you dont need to differentiate between right and left click remove the first if else)

bool leftClickedOnce = false;

if(leftmousebuttonclicked)
{
    if(leftClickedOnce)
    {
        leftClickedOnce = false;
        //doubleclick logic
    }
    else
    {
        leftClickedOnce = true;
    }
}
else
{
    leftClickedOnce = false;
}

if you want counts

int desiredClickCount = 2;
int leftClickCount = 0;

if(leftmousebuttonclicked)
{
    if(leftClickCount < desiredClickCount)
    {
        leftClickCount++;
    }
    else
    {
       leftClickCount = 0;
       //clickCountLogic logic
    }
}
else
{
   leftClickCount = 0;
}
0

I ended up following the method KYL3R suggested like so:

    void Update () 
    {
        if (leftMouseButtonWasClicked) { count++; CallOnClickCount(count); }
        count %= maxCount;
    }

    public void CallOnClickCount(int number)
    {
        switch (number)
        {
            case 1:
                //logic
                Debug.Log("logic " + count);
                break;

            case 2:
                //logic
                Debug.Log("logic " + count);
                break;

            case 3:
                //logic
                Debug.Log("logic " + count);
                break;
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.