Answer the question
In order to leave comments, you need to log in
How is it customary to make an item factory?
How is it customary to create a factory for items? For example, let's take the initial data:
There is a sword and a spear. They are listed in the prefab, have different sprites, etc., and a script hangs on them, for example:
class Weapon : MonoBehaviour
{
int id;
int damage;
}
public class Weapon
{
int id;
int damage;
public Weapon(int damage)
{
this.damage = damage;
id = ++id;
}
}
Answer the question
In order to leave comments, you need to log in
"But then the question arises, what if I want to store weapon sprites and transfer them to the sword model? After all, without MonoBehaviour, I won't be able to assign sprites in the inspector."
I would suggest storing such "Resources / Assets for weapons" separately.
Some list where, by the ID of the weapon, you can get a sprite, a text description, a model .. whatever.
Methods for working with a list is possible for convenience and all this encapsulation and so on.
Then the logic of the weapon will be conditionally separated from its presentation. If you want to show the sword - you got the sprite from the resources - and showed it. and the rest of the time we store a set of IDs.
Since there are many subscribers to the question, I will depict the current solution:
public class Item
{
public int id;
public int cost;
public string name;
public Sprite performance;
public Sprite icon;
public Item(int _cost, string _name, Sprite _perfomance, Sprite _icon){
id = ++id;
cost = _cost;
name = _name;
performance = _perfomance;
icon = _icon;
}
}
public class Weapon : Item
{
public int damage;
public int distance;
public Weapon (int _damage, int _distance, int _cost, string _name, Sprite _perfomance, Sprite _icon):base(_cost, _name, _perfomance,_icon)
{
damage = _damage;
distance = _distance;
}
}
public class Sword : Weapon
{
public Sword (int _damage, int _distance, int _cost, string _name, Sprite _perfomance, Sprite _icon):base(_damage,_distance, _cost, _name, _perfomance, _icon)
{
}
}
public Sprite GetSprite(string _name){
Sprite[] textures = Resources.LoadAll<Sprite>("Weapon/Swords");
string[] names = new string[textures.Length];
for(int ii=0; ii< names.Length; ii++) {
names[ii] = textures[ii].name;
}
Sprite sprite = textures[Array.IndexOf(names, _name)];
return sprite;
}
void Start()//для проверки
{
item_L.Add (new Weapon (10, 1, 111, "noobsword" , GetSprite ("noobsword"), GetSprite ("noobsword")));
item_L.Add (new Weapon (10, 1, 111, "epicsword" , GetSprite ("epicsword"), GetSprite ("epicsword")));
}
i.transform.FindChild("Text").GetComponent<Text>().text = currentItem.name;
i.GetComponent<Image>().sprite = currentItem.icon;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question