Change sprite of a UI image throug button click (c#)
I have four different images with a button component, and a script that looks like this:
public class GodSelect : MonoBehaviour {
GameObject S1;
GameObject S2;
// Use this for initialization
void Start ()
{
S1 = GameObject.Find("Skill 1");
S2 = GameObject.Find("Skill 2");
}
public void Thor()
{
Debug.Log("Thor selected");
}
public void Tyr()
{
Debug.Log("Tyr selected");
}
public void Skadi()
{
Debug.Log("Skadi selected");
}
public void Hel()
{
Debug.Log("Hel selected");
}
}
The debug part works. S1 and S2 are images. What I want to do is change the functions so whenever one function is activated, the sprites of S1 and S2 change to different sprites. For example, activating the Thor function will change the sprites of S1 to one sprite, and S2 to a different sprite. the Tyr function will do the same with two more different sprites, and so on.
I tried searching for an answer but I keep getting stuck and I don't know what to do anymore. If anyone can figure this out and help me, I'll be really grateful ^^
Answer by Hellium · Apr 11, 2019 at 08:50 PM
public struct God
{
public string Name;
public Sprite S1;
public Sprite S2;
}
public class GodSelect : MonoBehaviour
{
// Drag & drop the gameObject holding the image component in the inspector
public Image GodImage1;
// Drag & drop the gameObject holding the image component in the inspector
public Image GodImage2;
// Fill the array in the inspector
public God[] Gods;
// Specify this function in the `onClick` event of your buttons
// And give the name of the god you have set in the inspector
public void SelectGod( string name )
{
for( int godIndex = 0 ; godIndex < Gods.Length ; ++godIndex )
{
if( string.Equals( Gods[godIndex].Name, name, System.StringComparison.InvariantCultureIgnoreCase ) )
{
Debug.Log( Gods[godIndex].Name + " selected" ) ;
GodImage1.sprite = Gods[godIndex].S1;
GodImage2.sprite = Gods[godIndex].S2;
break;
}
}
}
}
You could do something better (IMO) by making God
inherit from ScriptableObject
, and defining SelectGod
as follow:
// Specify this function in the `onClick` event of your buttons
// And drag & drop the scriptable object in the inspector
public void SelectGod( God god )
{
Debug.Log( god.Name + " selected" ) ;
GodImage1.sprite = god.S1;
GodImage2.sprite = god.S2;
}
Your answer
Follow this Question
Related Questions
How to get Access of image as sprit in scripts 0 Answers
Managing multiple images fillamount by one function? 1 Answer
Keep button's image size same as original sprite 1 Answer
Save a Image's state 1 Answer
Button calls itself numerous times 0 Answers