- Home /
Why is Sprite a null?
So I have classes: Item , Weapon that inherits from Item , ItemFactory and some InventoryController. Code:
 public class Item : MonoBehaviour {
       protected float scale = 1;
       public float Scale { get
         {
           return scale;
         }
       }
       protected int id;
       protected int rarity;
       static protected Sprite sprite;
     
       public Item()
       {
         id = -1;
       }
     
       public Item(int id)
       {
         this.id = id;
       }
     
       public bool IsEmpty()
       {
         if(this.id==-1) return true;
         return false;
       }
     
       public Sprite getSprite()
       {
         return sprite;
       }
     
     }
 public class Weapon : Item{
 
   public Weapon()
   {
     scale = 0.25f;
     id = 1;
   }     
   void Awake()
   {
     sprite = GetComponent<Image>().sprite;
   }
 
 }
InventoryController calls to ItemFactory to make Item for it and then I use this code to set Item into inventory:
 public void AddItem(Item item)
   {
     for(int i=0; i<slotAmount; i++)
     {
       if (items[i].IsEmpty())
       {
         items[i] = item;
         GameObject itemObj = Instantiate(inventoryItem); // Its empty item prefab
         itemObj.transform.SetParent(slots[i].transform);
         itemObj.transform.position = slots[i].transform.position;
         itemObj.GetComponent<Image>().sprite = item.getSprite();
         itemObj.transform.localScale = new Vector3(item.Scale, item.Scale);
         return;
       }
     }
   }
 
Even thought scale comes right the sprite I get is null. Tried to Debug it and item.getType() returns "Weapon" if ItemFactory returns new Weapon. So the Question is why sprite I set to this item is null? I call the itemFactory like this:
 ItemFactory itemFactory = new ItemFactory();
 AddItem(itemFactory.makeItem(1)); // makeItem(int type) returns the Item of type Weapon if type == 1
 
I want every object of type Weapon to have the same sprite. Because its just for educational purpouses.
You declare sprite on line 10, but I don't see anywhere where you ever assign a value to it, so getSprite is just going to return null.
Look closely: 
 void Awake() { sprite = GetComponent().sprite; } Also Script is attached to UI->Image prefab 
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                