- Home /
Initialize button state icon by script
I try to create ui menu with script at start.
I use this for build menu:
...
void PopulateList () {
foreach (var item in itemList) {
GameObject newButton = Instantiate (sampleButton) as GameObject;
SampleButton button = newButton.GetComponent <SampleButton> ();
Button SampleButton = newButton.GetComponent <Button> ();
Sprite SpriteState = SampleButton.GetComponent <SpriteState> ().highlightedSprite;
button.name = item.name;
button.button.image.sprite = item.icon;
SpriteState = item.icon_h;
button.button.onClick = item.thingToDo;
button.tag = item.tag;
newButton.transform.SetParent (contentPanel);
}
}
...
and this attached on Prefab button:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SampleButton : MonoBehaviour {
public Button button;
public Image icon;
public Button icon_h;
}
At start this is the error message:
ArgumentException: GetComponent requires that the requested component 'SpriteState' derives from MonoBehaviour or Component or is an interface. UnityEngine.Component.GetComponent[SpriteState] () CreateModelScrollList.PopulateList () (at Assets/Libreria/Script/CreateModelScrollList.cs:73) CreateModelScrollList.Start () (at Assets/Libreria/Script/CreateModelScrollList.cs:62)
Where i am wrong? I am desperate...
Try choosing a different name for the sprite than "SpriteState".
try with this line:
button.button.spriteState.highlightedSprite = item.icon_h;
the error:
Assets/Libreria/Script/Create$$anonymous$$odelScrollList.cs(78,39): error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Selectable.spriteState'. Consider storing the value in a temporary variable
Answer by benfattino · Jul 24, 2015 at 08:35 PM
After 3 hour I find... Little bit complicate (for me)...
void PopulateList () {
foreach (var item in itemList) {
GameObject newButton = Instantiate (sampleButton) as GameObject;
SampleButton button = newButton.GetComponent <SampleButton> ();
Sprite newSprite = item.icon_h;
SpriteState st = new SpriteState();
st.disabledSprite = newSprite;
st.highlightedSprite = newSprite;
st.pressedSprite = newSprite;
SpriteState Spritebutton = st;
//button.nameLabel.text = item.name; !Attention!
button.name = item.name;
button.button.image.sprite = item.icon;
button.button.spriteState = Spritebutton;
button.button.onClick = item.thingToDo;
button.tag = item.tag;
newButton.transform.SetParent (contentPanel);
}
Your answer
Follow this Question
Related Questions
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
I need to move a sprite when an UI button is clicked 1 Answer
Can't interact with world space ui button when cursor mode is locked any solutions? 1 Answer