- Home /
Implementation of Items
Hello, I'm pretty new to Unity and just playing around with some stuff and now came to a point where I don't know if the solution I came up with really is a good way to do it.
I want to put items into the game. Static items with fixed attributes. Startin with a Heal Potion, I tried to make it really easy to create new items. My idea was to make a bunch of effects, than create the item and give them these effects with some concrete values. Therefor I create some classes in C#, like "potion" and then create a GameObject for each Potion I want and put the script on it, then give them the objects linked with the effects and some values.
Here is a simple example:
public class Effect : MonoBehaviour {
private List<GameObject> _target;
public Effect() {
_target = null;
}
public Effect(GameObject target) {
_target = new List<GameObject>();
_target.Add(target);
}
public List<GameObject> TargetList {
get { return _target; }
}
}
public class Heal : Effect {
public int _healing;
public void ApplyEffect(int amount) {
List<GameObject> targetList = this.TargetList;
foreach(GameObject target in targetList) {
if( target.GetComponent("playerStats") != null) {
target.GetComponent("playerStats").GiveLife(_healing)
}
}
}
}
public class Item : MonoBehaviour {
public int _id;
public int ItemID {
get { return _id; }
set { _id = value; }
}
}
public class ItemPotion : Item {
public GameObject[] effects;
public int[] _values;
public void Use() {
for(int i = 0; i < effects.Length(); i++) {
effects[i].GetComponent(effects[i].name).ApplyEffect();
}
}
}
Now I have 2 GameObjects, an effect and a potion. Would be easy to create another potion, with more healing maybe. But i think its a very complicated way to do this. Is there a more common way to do this?
You can't really have a $$anonymous$$onoBehaviour derived class with a constructor like that - you can't create instances of $$anonymous$$onoBehaviours directly - you have to use AddComponent.
But I'm not sure why these classes are $$anonymous$$onoBehaviours - they look more like static classes or singletons to me...
I'm just translating all the Code I did before from JavaScript to C#. Will test it out as soon as I'm done. -.-
This is similar to how I'm handling effects (and it is working nicely). An "Actor" has a "Stats", and an "Effect" has a "Stats", and when the effect is 'applied' it just adds the stats to the actor's stats based on the 'apply$$anonymous$$ethod', so, like, over-time or all-at-once, temporary or permanent, that kind of thing. I will add to Why's recommendation, these should probably be logical classes and not $$anonymous$$onoBehaviour extensions, to make them as easy as possible to use. That way an Item could have an Effect[] effects, which should still be Inspector-editable.
Your answer
![](https://koobas.hobune.stream/wayback/20220613073045im_/https://answers.unity.com/themes/thub/images/avi.jpg)