- Home /
How to extend the Highlight effect of a Unity Button
Hello,
I've been trying to make some custom UI elements that inherit from the Unity UI. Specifically I'm trying to have affect multiple images with the color tint of my button.
I managed this for OnSelect, OnDeselect and OnSubmit. I don't understand where I need to hook the Image recoloring for making the Button non-interactable and highlighting the Button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class SelectableButton : Button
{
//Variables
[SerializeField] private Image[] targetImages;
//Properties
public Image[] TargetImages{get{return targetImages;}}
//Public Methods
public override void OnSelect(BaseEventData eventData)
{
base.OnSelect(eventData);
if(OnSelectEvent != null) OnSelectEvent.Invoke();
tintTargetImages(SelectionState.Selected);
}
public override void OnDeselect(BaseEventData eventData)
{
base.OnDeselect(eventData);
if(OnDeselectEvent != null) OnDeselectEvent.Invoke();
tintTargetImages(SelectionState.Normal);
}
public override void OnSubmit(BaseEventData eventData)
{
base.OnSubmit(eventData);
tintTargetImages(SelectionState.Pressed);
}
//private Methods
private void tintTargetImages(SelectionState _state)
{
if(TargetImages != null)
{
for(int i = 0; i < TargetImages.Length; i++)
{
tintImage(_state,ref TargetImages[i]);
}
}
}
private void tintImage(SelectionState _state, ref Image _image)
{
if(_state == SelectionState.Disabled) _image.color = colors.disabledColor;
else if(_state == SelectionState.Highlighted) _image.color = colors.highlightedColor;
else if(_state == SelectionState.Normal) _image.color = colors.normalColor;
else if(_state == SelectionState.Pressed) _image.color = colors.pressedColor;
else if(_state == SelectionState.Selected) _image.color = colors.selectedColor;
else Debug.LogError("Invalid State entered. New State added to UI?");
}
//Public UnityActions
public UnityEvent OnSelectEvent;
public UnityEvent OnDeselectEvent;
}
That's the current state of my script. (The original idea was just to hook some UnityEvents that'd fire when the Button is selected/unselected).
not sure but you can use different sized sprites for button if you are using sprites.
Yeah that's a solution, but suboptimale for some of my purposes.
If I have a combination of different images (one for the button and one for whatever that button represents) it's pretty annoying to produce individual sprites for every possible combination. I figure it's easier to just tint the other image too.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to extend the Highlight effect of a Unity Button 0 Answers
How to drag objects from UI into scen 3 Answers
Overlay 2 scenes 1 Answer