Функция для создания спрайта и установки его цвета - PullRequest
1 голос
/ 21 сентября 2019

У меня есть элемент, созданный из базы данных SQL.

До сих пор я успешно использовал функцию GetSprite () ... Теперь мне нужна эта функция, чтобы изменить цвет спрайта, еслиуказан пользовательский цвет.


// 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;
         //   }
     }    
}

Можно ли что-то подобное сделать со спрайтом?Должен ли я переписать GetSprite () в GetImage ()?

Спасибо!

1 Ответ

1 голос
/ 21 сентября 2019

Спрайты не имеют цвета (изображения имеют)

Где у вас есть эта строка:

itemView.GetComponent<Image>().sprite = i.GetSprite();

Здесь вы можете установить цвет:

itemView.GetComponent<Image>().color = new Color(0,0,0,0); //fill in your own values here

Соответствующая документация

...