- Home /
I have objects that have the same set of variables, but different desired behaviors. How can I do this without repeating variable declarations across all behaviors?
I have a fairly sizable number of bullets in my game. Some will do things like seek the player out, some will do other things, but all of them will have a set of properties(speed, power, boolean(isPiercing), etc.)
My OOP-fu is a little weak, but I've wondered if inheritance might be the way to go. I'm not entirely sure how inheritance works with Unity, though.
I suppose I could make one script containing all of the variables, and assign them to each bullet prefab I have, and have all of their behavior scripts reference the other script attached to the object, but that seems like a really awkward and wasteful way of doing it. Is there a better way to do this using inheritance, or something else I might not be aware of?
Note: Currently using UnityScript as my language.
Answer by Piflik · Jan 09, 2013 at 12:29 PM
Inheritance is exactly what you need. Create a class, just like you normally would, put all your shared variables and methods in there. Then you create your actual bullet classes. Instead ov MonoBehaviour, you'd then extend your super-class.
UnityScript implicitely extends MonoBehaviour unless you do the class declaration yourself.
Not sure about the actual syntax, since I only ever did this in C#, but something along the lines of:
public class Bullet01 extends BulletBase {
//code here
}
You then only assign the sub-class to the bullet. All inherited variables will show up in the inspector.
Alright, that's what I expected. But how does that work script wise?
For instance, should I have bulletBase.JS contain the public class BulletBase, then declare bullets that extend bullet base in each script?
$$anonymous$$g.
BulletBase.js:
public class BulletBase extends $$anonymous$$onoBehavior{
//Variables(e.g, Speed), object cleanup, other code.
}
SeekingBullet
public class SeekingBullet extends BulletBase{
//code that follows player, at Speeds defined in through Inspector thanks to BulletBase?
}
Then I should attach SeekingBullet.js to a prefab for my seeking bullets, and leave BulletBase.js unattached?
Exactly. The sub-class will inherit all properties of the super-class and they will show up in the inspector. You SeekingBullets script will first show all variables of the BulletBase class and then all of its own variables. The super-class doesn't have to be assigned to an object.
You can of course use the BulletBase script for the most basic bullets, if you want to, and extend it with the sub-classes for the special bullets. All variables/methods of the super-class that you want to have differently in the sub-classes would then have to be overriden.