Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Whats the best way to make a button (image) C#

Discussion in 'UGUI & TextMesh Pro' started by FlashX, Sep 27, 2015.

  1. FlashX

    FlashX

    Joined:
    Nov 16, 2013
    Posts:
    51
    Hi guys,

    Sorta new to this..

    Whats the best way to go about making a UI Image button? Ive seen some people use a button and somehow change the background of it (i cant seem to get that happening) and ive seen others that use a Panel.

    Any feedback would be great!

    Cheers
     
  2. BinaryX

    BinaryX

    Joined:
    Aug 4, 2014
    Posts:
    55
    https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button

    At 0:45 it explains what's required for a Button to work. It says :
    So what you need to do is to Right click in the Hierarchy -> UI -> Button. Then you can delete that optional text element. After that you go to the Image script and change the Source Image to the image that you want to use. Then play with the settings that are there in order to get it exactly the way you want (Image Type, Preserve aspect for normal image type, Fill center for sliced image type, color etc.)
     
  3. mafanbong8819

    mafanbong8819

    Joined:
    Feb 2, 2017
    Posts:
    8
    Code (CSharp):
    1. mybutton.image.overrideSprite = blockA_disable;
    tested. worked.




    the whole script is as following,
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. [RequireComponent(typeof(Button))]
    7. public class disable : MonoBehaviour {
    8.  
    9.    
    10.     public Sprite blockA;
    11.     public Sprite blockA_disable;
    12.     public bool condition;
    13.     public Button mybutton;
    14.     public int counter;
    15.  
    16.     void start()
    17.     {
    18.         mybutton = GetComponent<Button> ();
    19.     }
    20.  
    21.     public void changebutton()
    22.     {
    23.         counter++;
    24.         if (counter % 2 == 0) {
    25.             mybutton.image.overrideSprite = blockA;
    26.                  //condition for working button.
    27.         } else {
    28.             mybutton.image.overrideSprite = blockA_disable;
    29.                  //condition for disable button
    30.         }
    31.  
    32.     }
    33.  
    34. }
    35.  
     
    mafanbong likes this.