Dev Stories: is Unity OnGui still good?

Okay so here’s the million-dollar question for you guys:

What game mechanic is used in every RTS, RTT or any game, in which you have to control your soldiers, goons or minions or any sorts of units?

Yep you guessed it right, and there’s no official(at least that I'm aware of) name for it. We at Golden Fox call it The Box Selection.

As you may already know, NEILA is an Action RPG with strategic game elements. This means you get to control your goons alongside the main hero. We are obviously in need of a precise Box Selection. Also, we need it in our level editor DragonFly too. That’s where we faced an issue for the first time. The thing is that our selection works just fine, but it’s still not quite there in terms of performance, selection box appears a little late after the mouse click.

GIF

 

If you look closely, you will notice tiny lag before the rectangle shows up. In bigger scenes, it becomes almost unusable.

And here’s how the code looks like:

private void Update()
{
   if (Input.GetMouseButtonDown(0))
   {
      SaveMouseStartingPosition(Input.mousePosition);
   }
}
private void SaveMouseStartingPosition(Vector3 startingPos)
{

}

At first, I thought that the problem was with Selection Rect itself, but that wasn’t the case. I dug it up and what do you know? The problem was Unity’s Input System itself. It depends on Frame rate and Selection is a little too late most of the time.

I’ve tried to save the mouse position on each Update() call, to compare them in the next, but that was a really bad solution. I also tried to use FixedUpdate(), but it didn’t help either. So I asked myself, what’s called more often than Update() or FixedUpdate()? After a subtle blackout, the Eureka moment kicked in!
It is OnGui ffs, It can be called several times per each frame and it can detect mouse click almost instantly.

Here's the code:

private void OnGUI()
    {
        var e = Event.current;
        if (e.button == 0 && e.isMouse)
            SaveMousePositionOnBoxSelectionStart(e.mousePosition);
    }

    private void SaveMousePositionOnBoxSelectionStart(Vector3 mousePos)
    {
        
    }

 

GIF

 

This how I solved the box selection performance problem. Really simple. I hope you will find it, useful guys.  If any of you have encountered a similar problem or found a better workaround to the problem let me know in the comments down below.

Signing out,

Gia

One thought on “Dev Stories: is Unity OnGui still good?”

Leave a Reply

Your email address will not be published. Required fields are marked *