Toggle input with sprite swap instead of checkmark?
Hi folks!
I'm trying to make a toggle input (in Unity 5 using canvas), but I need it swap the sprite rather than overlay a checkmark sprite on top of the backgrund sprite. Since my sprites are decorated with transparent cut-outs I can't just overlay one with the other..
Any ideas? It seems like a pretty common use case to me..
Peace - Viggo
Answer by TheGering · Aug 03, 2016 at 08:18 AM
here another version, use toggle as usual, but with this component attached the background is disabled/hidden, when checkmark is shown:
using UnityEngine;
namespace UnityEngine.UI
{
[ExecuteInEditMode]
public class ToggleGraphicSwap : MonoBehaviour {
Toggle _toggle;
Toggle toggle {
get { return _toggle ?? (_toggle = GetComponent<Toggle>()); }
}
void Awake() {
toggle.onValueChanged.AddListener(OnTargetToggleValueChanged);
}
void OnEnable() {
toggle.targetGraphic.enabled = !toggle.isOn;
}
void OnTargetToggleValueChanged(bool on) {
toggle.targetGraphic.enabled = !on;
}
}
}
Answer by Miguel-Ferreira · Sep 30, 2015 at 07:56 AM
I ended up using this
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ToggleSpriteSwap : MonoBehaviour {
public Toggle targetToggle;
public Sprite selectedSprite;
// Use this for initialization
void Start () {
targetToggle.toggleTransition = Toggle.ToggleTransition.None;
targetToggle.onValueChanged.AddListener(OnTargetToggleValueChanged);
}
void OnTargetToggleValueChanged(bool newValue) {
Image targetImage = targetToggle.targetGraphic as Image;
if (targetImage != null) {
if (newValue) {
targetImage.overrideSprite = selectedSprite;
} else {
targetImage.overrideSprite = null;
}
}
}
}
@$$anonymous$$iguel Ferreira THAN$$anonymous$$ YOU, this code works perfect and is exactly what I needed to know!
Answer by ptblk · Mar 12, 2016 at 02:35 PM
where do you attach this? I cant seem to see anything change. I have put it onto my canvas, linked the toggle and sprite, but nothing happens
Answer by HyunMok_Moon · Nov 16, 2020 at 02:05 AM
put this code after line 20 and line 22.
if (newValue) {
targetImage.overrideSprite = selectedSprite;
targetImage.enabled = false;
} else {
targetImage.overrideSprite = null;
targetImage.enabled = true;
}
When toggle on, Checkmark will show, and targetImage(Background) hide. Toggle off, Checkmark will hide, and targetImage(BG) will show.