Reputation: 67
I have an item which is created from a SQL Database.
I have been using a GetSprite() function successfully until now... Now I need this function to change the color of the sprite if a custom color is specified.
// The Items come from a SQL database
[System.Serializable]
public class Consumable : Item
{
// inherits public string Name;
// inherits public string ImagePath;
//specific to derived class Consumable
public string CustomColor = "";
public override Sprite GetSprite()
{
Sprite newSprite = Sprite.Create(Resources.Load<Texture2D>(ImagePath),
new Rect(0, 0, 64, 64), new Vector2(0.5f, 0.5f));
if(CustomColor != "")
{
// Change the color here
// Color col;
// ColorUtility.TryParseHtmlString(CustomColor, out col);
// newSprite.color = col; <--- I wish!
}
return newSprite;
}
public override bool IsConsumable()
{
return true;
}
}
public class ShowInventory : MonoBehaviour
{
// set in the inspector
// the itemViewPrefab object has a component of type Image
public GameObject itemViewPrefab;
// get a list of Items
List<Item> playersItemsFromTheDB = DBAccess.GetAllItemsForMyPlayer();
foreach(Item i in playersItemsFromTheDB)
{
//instantiate the itemViewPrefab (in the real app this forms a grid)
GameObject itemView = Instantiate(itemViewPrefab);
// set the Image for the item
itemView.GetComponent<Image>().sprite = i.GetSprite();
// HERE we could change the Image color but I would need to add this
// to about 100 different spots so it would be really nice if it
// was in the Consumable class. THE FOLLOWING DOES WORK:
// if( i.IsConsumable() && (i as Consumable).CustomColor != "") {
// Color newColor;
// ColorUtility.TryParseHtmlString((i as
// Consumable).CustomColor, out newColor);
// itemView.GetComponent<Image>().color = newColor;
// }
}
}
Is it possible to do something like this to a sprite? Should I rewrite GetSprite() to be GetImage()?
Thanks!
Upvotes: 1
Views: 77
Reputation: 15951
Sprites don't have a color (images do)
Where you have this line:
itemView.GetComponent<Image>().sprite = i.GetSprite();
This is where you can set the color:
itemView.GetComponent<Image>().color = new Color(0,0,0,0); //fill in your own values here
Upvotes: 1