- Home /
Unity 4.6 Change Highlighted Button Sprite using C#
Hi there,
I am currently using the SpriteSwap transition mode for a button in the Unity 4.6 beta, and was wondering if there is there a way to permanently change the highlighted sprite from the original assigned in the Inspector through code when that button is pressed?
Did you solve it? I have the same problem and can't find any way to set the highlighted sprite.
Answer by kolibro89 · Mar 27, 2015 at 04:55 PM
I'm so happy, I've found an answer that worked for me here:
Sprite newSprite = Resources.Load<Sprite>("sprites/somesprite");
SpriteState st = new SpriteState();
st.disabledSprite = newSprite;
st.highlightedSprite = newSprite;
st.pressedSprite = newSprite;
_button.spriteState = st;
I think that means that you cannot access the variables in the existing SpriteState, but you can just create a new SpiteState that overrides the old one :-D
Answer by Anxo · Oct 24, 2014 at 07:12 PM
It looks a little tricky at the moment, Its very fresh meat and needs to get a good cooking. But I think its the image variable in the selected stuff.
http://docs.unity3d.com/460/Documentation/ScriptReference/UI.Selectable.html
I have not been able to test it as I have not been able to access the UI namespace yet
But I think this answer might get you a little closer to a solution http://answers.unity3d.com/questions/780629/unity-46-gui-select-button-via-script.html
a little convoluted right now and I am sure it will change.
So, has this changed? I still can't find a solution how to get/set the sprite that is used for different states like pressed etc.
Answer by Corefinder · Mar 25, 2015 at 11:37 PM
Here is something I found on another post: using UnityEngine; using UnityEngine.UI; using System.Collections;
public class TestMenu : MonoBehaviour
{
/// <summary>
/// This is the Sprite we're going to swap to.
/// </summary>
/// <remarks>
/// This is set in Unity's Inspector.
/// </remarks>
public Sprite OtherSprite;
/// <summary>
/// The Array of Images.
/// </summary>
Image[] images;
// Use this for initialization
void Start()
{
// Get all components of type Image that are children of this GameObject.
images = gameObject.GetComponentsInChildren<Image>();
// Loop through each image and set it's Sprite to the other Sprite.
foreach (Image image in images)
{
image.sprite = OtherSprite;
}
}
}
Your answer
Follow this Question
Related Questions
Buttons are fully functional but have never highlighted or pressed down in my 1+ year unity journey. 1 Answer
[4.6 UI] Possible to reference parameter of OnClick persistent event? 0 Answers
Unity 4.6 Beta Controller Menu Button Movement 0 Answers
I made an resume button, but I don't know how to code it to close my pause menu, any tips? 2 Answers
How to make UI buttons so my player can move along certain lines 0 Answers