1
votes

I'm makimg a game in Unity using C# developed for Android. I'm testing using Unity Remote 4. I was just wondering if a sprite can be used as a button in Unity rather than the button made in Component -> UI -> Button.

I've tried this:

private void Update() 
{
     if (Input.touchCount > 0) 
         Application.LoadLevel("startScene");
}

Which does work. The button is being used to switch from the main menu to an options menu.

Ideally, I want the button to be in the same place in the options menu to be used to go back to the main menu. The problem then is that because the scenes switch instantly, the scenes switch between each other over and over I guess because the next scene gets the touch input as well.

How can I delay the time between the scenes switching, or is there a better way to use sprites as a button??

4

4 Answers

1
votes

You can create a menu system which is persistent in scenes. Have a look at This Tutorial Video for guide

0
votes

Usually buttons perform their function once a tap has been performed. A tap is a press and release on the button. What you are doing is performing your function on a press which is causing your buttons to be triggered continuously while you hold your finger.

Pseudo code: If a finger presses on the sprite If the same finger is release on the sprite The button has been pressed.

0
votes

You can use ray casting to detect touch on the sprite

private void Update()
{
    if (Input.touchCount != 1) return;

    var wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
    var touchPos = new Vector2(wp.x, wp.y);

    if (collider2D == Physics2D.OverlapPoint(touchPos))
    {
        // Your code
    }
}
0
votes

This is one way that has worked for me:

  1. Add the sprite that you will use as the background of the button to the stage.
  2. Add a Collider and mark it as a trigger.
  3. Assign a script where you add any of the following functions depending on your case.
private void OnMouseDown () {
     // Runs by pressing the button
}


private void OnMouseUp () {
     // Runs when button is released
}