Using Data with a Button?
Hello,
(What I am doing) What I am doing is I have a button prefab in a scrollable panel. The button and its text is loaded through WWW, as well as instantiating more prefabs for each button needed.
When a user clicks on one, it should use an IEnumerator to load the story associated with that title and then open a new panel with the story loaded. So what I was thinking was attaching a C# script to the panel holding the button prefabs and when a button is clicked, it will load the story associated with that button ID via WWW.
(The Problem) My question is how the buttons know which story to load? My idea was to attach and use the prefab's C# script to hold the story ID and when it's clicked: the main script can ask that C# script what ID it was. How do I do that though, and also change the script's ID for every new button i instantiate?
Answer by KuR5 · Jun 06, 2016 at 01:37 PM
@Rotavele, you have got the right idea to deal with your requirements and here is my help to you for your stuff. Ask me further if you will have any regards with this.
/// Instantiates the button prefab for each story.
/// <param name="storyId">Story identifier.</param>
void InstantiateButtonPrefab(int storyId)
{
GameObject go = Instantiate(buttonPrefab) as GameObject;
go.GetComponent<Button>().onClick.AddListener(()=>{
//when this button clicked, it will load the story wrt storyId
LoadStory(storyId);
});
//do your stuff
}
/// Loads the story.
/// <param name="storyId">Story identifier.</param>
void LoadStory(int storyId)
{
//do your stuff
}
Your answer
Follow this Question
Related Questions
Can you pass a RawImage to an IEnumerator in another script? 0 Answers
Script loads wrong information 0 Answers
LoadScene not Working 1 Answer
Change public variable with button 1 Answer
AddListener not working after build 0 Answers