Mirac7
Mirac7

Reputation: 1646

Add children from array

I've been trying to learn swift for a few days now, and all tutorials I've found had had a specified number of SKNodes. I'm trying to programmatically add new instances to an array nodeList and add them to the scene, because I want each of them to execute some code periodically. This is my current version of code for adding more objects:

if (last_created < 0)  {

    //Some other code here

    for i in 0...3 {
        self.nodeList.append(self.backObject);

        var x_current = CGFloat(Float(arc4random())/4294967296.0 * Float(x_range) + Float(x_min));
        var y_current = CGFloat(Float(y_min) - Float(y_range));

        self.nodeList[self.nodeList.count-1].position = CGPoint(x: x_current, y: y_current);
        self.addChild(self.nodeList[self.nodeList.count-1]);
    }
}

Attempt to execute this raises an exception:

Attemped to add a SKNode which already has a parent

I assume that every item in my nodeList array is seen as the same object, rather than separate instances. However, I don't know how to fix the problem. How should I have done this?

Thanks for your help.

Upvotes: 0

Views: 529

Answers (1)

0x141E
0x141E

Reputation: 12753

You are adding self.backObject to the array multiple times, so it is being added to the scene more than once, causing the error. You should create a new instance of the node within the loop and add that to the array.

Upvotes: 1

Related Questions