So I hav a object called BasicSword which is a der...
# getting-started
o
So I hav a object called BasicSword which is a derived class of MeleeWeapon, and in a object called BasicSoldier i hav some code like this:
Copy code
object BasicSoldier {
   fun init() {
      this.meleeWeapon = BasicSword
      .....
    }
    lateinit var meleeWeapon : MeleeWeapon
How do i instantiiate the BasicSword object ? It has a fun init() method which is used to instantiate it. Pls help
a
you can only initialize it from outside
BasicSoldier.meleeWeapon = BasicWord()
somewhere in your code
s
an
init { ... }
block is not the same as a
fun init()
by the way
should
BasicSoldier
be a singleton? that’s what top-level named `object`s are
o
im making BasicSoldier a object since i dont want to go on creating tons of BsicSoldier objects in my game, which could add to the memory requirements
s
I mean, you only get the one BasicSoldier like that
if you need more than one instance, you may end up sharing state between all of them
I’m no game designer, but perhaps you want an object pool instead?
r
An object is something that you'll only ever have one instance of. For all other types of things, you want a normal class.
But if that's actually what you want, you can do this:
Copy code
object BasicSoldier {
    var meleeWeapon: MeleeWeapon = BasicSword
}
That will initialize the weapon with BasicSword the moment the object ist first used (as that is also when the object is actually created in memory)
o
I know i can do that @robin but BasicSword is a object as well How do i instantiate BasicSword to meleeWeapon so that it doesnt give me errors later?
sorry I had gone asleep, it was 2 am in the morning yesterday
r
Why should it give you errors later? BasicSword being an object means that it gets instantiated automatically as soon as it is used. Without seeing the code of BasicSword I can't see anything inherently wrong with the code I posted.
o
nvm i solved it