Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Sp33dy_Sn1pa · Oct 11, 2014 at 02:15 PM · guigui.button

How to make GUI buttons react when pressed?[C#]

My GUI buttons work strangely. When pressed on touchscreen, they only react when the finger releases the button. After the finger leaves the button, the button stays in a pressed position. When I double tap the button, it performs the way I want it to which is as a single press and release. My question is, how do I make the button react as if it has been pressed and released when I touch it once?

Here is the code:

 using UnityEngine;
 using System.Collections;
 
 public class SnakeHead : MonoBehaviour
 {
     public float fTurnRate = 200; // Degrees of turning per second
     public float fSpeed = 9.5f; // Units per second of movement
     public Tail var;    
     public bool dead = false;
     public bool FlyUp = false;
     public bool FlyDown = false;    
     public bool debugMode = false;
     public bool centerButton = false;
     public Texture2D buttonImage = null;
     public Texture2D otherImage = null;
     public Texture2D currentImage = null;
     public string buttonLabel = "Fly Up";
     public string otherbuttonLabel = "Fly Down";
     
     private Rect currentRect = new Rect(15, 15, 150, 150);
     private Rect otherRect = new Rect(15, 300, 150, 150);
 
     //public string title = string.Empty;
     public GUISkin skin = null;
     public bool ButtonOnPress(Rect currentRect, Texture currentImage)
     {
         GUI.DrawTexture (currentRect, currentImage);
         if( Input.touchCount == 0)
         {
             return false;
         }
         foreach (Touch touch in Input.touches)
         {
             if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
             {
                 if(currentRect.Contains(touch.position))
                 {
                     return true;
                 }
             }
         }
         return false;
     }
     
     void Awake()
     {
         FlyUp = false;
         FlyDown = false;
     }
     
     public void OnGUI()
     {
         if (debugMode || Application.isPlaying)
         {
             if (centerButton)
             {
                 currentRect.x = (Screen.width * 0.5f) - (currentRect.width * 0.5f);
                 currentRect.y = (Screen.height * 0.5f) - (currentRect.height * 0.5f);
                 otherRect.x = (Screen.width * 0.5f) - (otherRect.width * 0.5f);
                 otherRect.y = (Screen.height * 0.5f) - (otherRect.height * 0.5f);
             }
             
             if (GUI.Button(currentRect, buttonLabel))
             {
                 FlyUp = true;
                 FlyDown = false;
             }
 
             if (GUI.Button(otherRect, otherbuttonLabel))
             {
                 FlyDown = true;
                 FlyUp = false;
             }
         }
     }
     void Update()
     {
         if (FlyUp)
         transform.Rotate (Vector3.forward * fTurnRate * Time.deltaTime);
         
         if (FlyDown)
         transform.Rotate (-Vector3.forward * fTurnRate * Time.deltaTime);
         
         transform.localPosition = transform.localPosition + transform.right * fSpeed * Time.deltaTime;
         
         var.TailUpdate();
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by fafase · Oct 11, 2014 at 02:50 PM

All buttons in Unity seem to be OnRelease, if you want to trigger an action on press, you need to come up with your own implementation. By the way, why not using the new uGUI?

Anyway, one way I could recommend is to create a wrapper method to draw the texture and check for press:

 public bool ButtonOnPress(Rect rect, Texture texture)
 {
     GUI.DrawTexture (rect, texture);
     if( Input.touchCount == 0)
     {
        return false;
     }
     foreach (Touch touch in Input.touches) {
        if (touch.phase == TouchPhase.Began)
        {
             if(rect.Contains(touch.position))
             {
                  return true;
             }
        }    
     }
     return false;
 }

This would be called in OnGUI since it contains a GUI method, you could also use a GUITexture so that you do not need the OnGUI call. Pretty much the same though using http://docs.unity3d.com/ScriptReference/GUIElement.HitTest.html

If you were to use the new uGUI, you just add a button and a script like this:

 using UnityEngine;
 using UnityEngine.EventSystems;   // This one needed
 
 public class MyScript : MonoBehaviour, IPointerDownHandler  // this interface needed
 {
 
     public void OnPointerDown(PointerEventData ped)
     {
         print ("Pressed");
     }  
 }

The you just need to drop that script on the object having the button component

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Sp33dy_Sn1pa · Oct 11, 2014 at 03:46 PM 0
Share

Hello fafase. I tried the first code and it gave me a lot of red errors. I isolated the issues(bracket misplacement on my part). I am down to one red error "SnakeHead.ButtonOnPress(Rect, Texture)' must have a body because it is not marked abstract, extern, or partial" and I'm not sure exactly what that means but I am diligently researching. I edited my code above to reflect your recommendations. I haven't made any changes to it yet or played around with it other than to clear the red out. Did I place the "public bool ButtonOnPress(Rect rect, Texture texture)" in the correct place?

avatar image Sp33dy_Sn1pa · Oct 11, 2014 at 04:04 PM 0
Share

Okay, so now I feel like a fool. I looked it over again and pasted the entire selection of code just before the Awake area. I got no red errors from it so I'm assu$$anonymous$$g that puts me on the right track, but you were saying that it would go in OnGUI and now I'm lost again because i see no difference in the way the buttons operate. I will change my posted code again.

avatar image Sp33dy_Sn1pa · Oct 11, 2014 at 04:40 PM 0
Share

Oh and I didn't realize the 4.6 beta was out, I'm downloading it now. I assume that's where the uGUI comes into play. I'm still pretty new to this so please bare with me if I don't perform correctly and thank you very much for your assistance.

avatar image fafase · Oct 11, 2014 at 09:20 PM 0
Share

Yep, pb is that the phase I copy pasted is ended/canceled which obviously is not what you want, Began is the one...my bad. I fixed it.

avatar image Sp33dy_Sn1pa · Oct 12, 2014 at 07:31 PM 0
Share

Well I've tried it again and again. I might not be comprehending your instructions, I am still learning. I'm getting a lot of mixed results though when I try other variations of my code not including the addition of the code you provided. The strangest issue I've run into is one where the button only works once and then it doesn't register any more presses after that. It seems like it should be a simple fix. I've been watching tutorials on the changes in 4.6 but I haven't found much in the way of accessing controls for the player when the controller script is attached to the player. I thought OnGUI was my best bet for that but I was wrong. Thanks for the tips though. I will just keep trying stuff until it works.

avatar image
0

Answer by 767_2 · Oct 11, 2014 at 02:44 PM

use this code it might help

link

    if(Input.touches.Length == 1)
             {
             Touch touch = Input.touches[0];
     
             if(touch.phase==TouchPhase.Began && guiTexture.HitTest(touch.position))
              {
                 //do something
     }
 
 
 }

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Sp33dy_Sn1pa · Oct 11, 2014 at 03:43 PM 0
Share

Sorry 767_2, but that uses JS and after trying it and researching how to access my C# code from the JS code, I think that moving my files into different folders to get it to work is a little inefficient. I appreciate the response though.

avatar image 767_2 · Oct 11, 2014 at 04:22 PM 0
Share

i interpreted to c#

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

button with content in multiple colors 3 Answers

Simulate IMGUI button press 1 Answer

Unity GUI Nested If statements causing GUI Buttons not to render 1 Answer

GUI.Button doesn't show texture 0 Answers

(Unity 4.6) Button animations 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges