- Home /
Question by
Omti1990 · Feb 03, 2021 at 10:51 AM ·
c#uiinherited-members
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).
Comment
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
Find out if gameObject is UI in 4.6 1 Answer
Options UI over all scenes 1 Answer