我已经扩展了SKSpriteNode并希望在其init函数中设置其name属性:
class Ship: SKSpriteNode {
var id: Int
/**
* Image name of sprite image for this bubble.
**/
var image: String
//some other vars but NOT name, because its super class SKNode has already name
init(ship: (name: String, <other vars>), position: CGPoint) {
let texture = SKTexture(imageNamed: self.image)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.name = name //here I set its name!!!
self.position = position
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
self.physicsBody!.dynamic = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
但是后来,当我创建一个“船舶”时。 with(ship [1]是包括名字在内的一些值):
var titanic = Ship(ship: ship[1], position: shipPosition!)
println(titanic.name) //nil
self.addChild(titanic)
titanic.name = 'titanic'
println(titanic.name) //titanic
如您所见 - 初始化时未设置名称 - 我必须在创建后设置它。
如何在init方法中设置此名称?或者我必须在创建之后才将其命名?
答案 0 :(得分:2)
在这种情况下,self.name = name
实际上意味着与self.name = self.name
相同。
您正尝试在tuple中传递变量,因此您可能需要self.name = ship.name
。 (甚至name = ship.name
。)
或者,您可以将这些全部作为参数直接传递给初始化程序:
init(named name: String, <other vars>, position: CGPoint) {
// ...
self.name = name
}
Ship(named: "titanic", <other vars>, position: shipPosition!)
答案 1 :(得分:0)