Toggle Unity3D Sprites On Click

When creating a game there is often the need to create a toggle.  An obvious example might be for a volume controller.  Click the sprite to turn the volume on, and click the same sprite to turn the volume off.

The best way to accomplish this task is to create a sprite game object that has a script with two public sprite variables.  In the Unity editor add one sprite that will represent the on toggle position and another sprite that will represent the off toggle position.

The above code represents a simple volume toggle.  The start method will cache our sprite renderer component and set the volume to whatever it was set to previously by reading the PlayerPrefs object.  In the update method, when the toggle is clicked, the volume is set to the inverse.  If the volume / sprite is in the on position then the renderer will draw the off sprite and set the volume to off.

The isTouched() method is very simple.  It has been designed to work for mobile (touch) and computers (click).  If a touch is detected and it has ended, then return true.  Same thing happens if a click has ended.  The method was designed to detect the end of a touch / click because often a touch down or mouse down will register multiple times causing the toggle to not perform as it should.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.