- Home /
Question by
harshuHere · Aug 31, 2019 at 04:46 AM ·
spritevariableimage
How do i add variables to a sprite ?
Hi , I am trying to make a game where a person has to classify images. As a simple example, an image of a parrot will show up and the user will have to determine whether its a bird or an animal. How do i add a variable to a sprite so that I can code in the logic that says: If --> user clicks on button animal AND sprite is an animal return TRUE How to tell unity that a particular sprite contains the image of a bird or an animal or whatever....
Comment
Best Answer
Answer by Hellium · Aug 31, 2019 at 06:17 AM
Since you can't "add a variable to a sprite", you simply define a data structure containing your sprite and all the information about your image.
[System.Serializable]
public class SpriteData //do not inherit from MonoBehaviour
{
public Sprite Sprite; // drag & drop parrot sprite
public string Name; // specify "parrot"
public string Type; //specify "bird"
}
In your "game controller" class:
public SpriteData[] SpriteData;
public Button ButtonPrefab;
private void Start()
{
for( int i = 0 ; i < SpriteData.Length ; ++i )
InstantiateImage( SpriteData[i] );
}
private void InstantiateImage( SpriteData spriteData )
{
Button button = Instantiate( ButtonPrefab );
button.GetComponent<Image>().sprite = spriteData.Sprite;
button.onClick.AddListener( () =>
{
Debug.Log( "Clicked on " + spriteData.Name + " " + spriteData.Type );
});
}