1

I am trying to create an array that will store my class objects. The createEnemies method is called when a level is started. Which should then create the enemy objects. However I don't understand how to do that. It should be created after "if(levelNumber < 5)"

class level {
    class func createEnemies() {
        numEnemies = Int(floor(levelNumber * 1.5 + 10))
        println("Number of Enemies this level: \(numEnemies)")

        if(levelNumber < 5){
            //Create numEnemies amount of class objects

        }
    }
}

//Enemy Variables
var enemiesKilled = 0

class enemy {
    class func enemiesKilled() {

    }

    class standard {

        var health:Int = 10
        var name:String = "Standard"
        var worth:Int = 10
        var power:Int = 10

        init () {

        }

        func kill() {

        }

        func damage(damage: Int) {
            self.health -= damage
            println("\(self.name) was damaged \(damage)")
            if(self.health <= 0){
                self.kill()
            }

        }
    }

3 Answers 3

2

For Swift 3.1

var enemies:[enemy] = [enemy]()
Sign up to request clarification or add additional context in comments.

Comments

1

Create an array of elements of a custom class like this:

var enemies = [enemy]()

You can add elements to it like this:

enemies.append(anEnemy: enemy)

Comments

1

If you want to have a specific number of enemies in the array there are several ways to achieve this (I write Enemy instead of enemy because the first letter of a class name is usually uppercase):

// "old fashioned" for loop
var enemies = [Enemy]()
for _ in 1...numEnemies {
    // call initializer of Enemy
    enemies.append(Enemy())
}

// my personal preference (Range has a method named map which does the same as Array)
// without the "_" you could also access the numbers if you want
let enemies = (1...numElements).map{ _ in Enemy() }

If you need to access the array later on you should declare the variable under your comment //Enemy Variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.