- Home /
How should I create/instantiate a skill/enemy/item
I was wondering what's the correct way to create/instantiate skills, enemies and items with varying parameters.
In my case it would be creating a custom skill to be thrown on field based on player's stats/skills. The skill has variables like damageFrom, damageTo, duration, delay and sometimes there can be a custom variable.
My current game is based on instantiating where it instantiates an empty object with my "BaseSkill" script. Then I was searching for a way to set these mentioned parameters and I ran into a way suggesting something like this:
skill1 = clonedPrefab.GetComponent<BaseSkill>().setDamage(1,3);
skill1 = clonedPrefab.GetComponent<Basekill>().setDuration(3);
....
... which looks a bit heavy, especially if there can be dozens of this same action happening at the same time. Should I go with objects as I'm working with C#, or something else? An example or link to a better way would be appreciated. Haven't done objects with C# before
Answer by robertbu · Sep 30, 2013 at 07:29 PM
You want to create a reference and then set them via that reference. You don't want to call GetComponent() for each one. Plus your syntax is wrong here (i.e. it would not compile).
BaseSkill skill1 = clonedPrefab.GetComponent< BaseSkill >();
skill1.SetDamage(1,3);
skill1.SetDuration(3);
Note by convention Methods and Classes start with a upper case letter. Variables start with a lower case letter. Nothing enforces this convention, but folks on the list expect it and therefore find code not written to this convention harder to read.
Thanks Robertbu. The code was just for demonstrating purposes anyway and it's not actually written anywhere.
So instantiating is the best way to make skills/enemies/items or was this just a suggestion to make my way work?
I've have to understand more about your skills and their relationship to the character to make a recommendation, and even then I'm not the expert. As a guess based on this limited information, I would suggest building your skills out of classes not derived from $$anonymous$$onobehaviour. These would be "standard" classes that would not require a game object to exist. In other words, they would not be components. You would create them with a 'new' operator and assign them to a parameter in your character or object.
And then there is the whole question of how you handle conceptually different skill sets. In the limited number of times I've had this issue, I've created a base class and derived the individuals from that base class. But there is a very interesting answer by @whydoidoit that suggest other approaches might be better:
http://answers.unity3d.com/questions/545157/how-to-store-a-javascript-in-a-variable-in-the-edi.html
I don't know if this is an issue for your skills.
Your answer
![](https://koobas.hobune.stream/wayback/20220613115102im_/https://answers.unity.com/themes/thub/images/avi.jpg)