从 Sprites UserData 中保存和读取信息
Saving and Reading information from a Sprites UserData
我正在尝试将一个值保存到 sprite 的用户数据中并能够读取它。
这是我所拥有的,由于某种原因,该值从未被保存并保持为零。
import SpriteKit
let frame = SKScene()
func createSprite() {
let sprite = SKSpriteNode()
sprite.userData?.setValue("100", forKeyPath: "key")
frame.addChild(sprite)
}
createSprite()
for child in frame.children where child is SKSpriteNode {
print(child.userData?.valueForKey("key") as? String)
//prints the value saved in the childs user data
if child.userData?.valueForKey("key") as? String == "100" {
print("It was a Success!")
}
if child.userData?.valueForKey("key") as? String == nil {
print("There was a problem :(")
}
}
我认为您的问题是 userData 开始时为 nil。试试这个...
func createSprite() {
let sprite = SKSpriteNode()
//init NSMutableDictionary
sprite.userData = NSMutableDictionary()
sprite.userData?.setValue("100", forKeyPath: "key")
frame.addChild(sprite)
}
希望对您有所帮助。
我正在尝试将一个值保存到 sprite 的用户数据中并能够读取它。
这是我所拥有的,由于某种原因,该值从未被保存并保持为零。
import SpriteKit
let frame = SKScene()
func createSprite() {
let sprite = SKSpriteNode()
sprite.userData?.setValue("100", forKeyPath: "key")
frame.addChild(sprite)
}
createSprite()
for child in frame.children where child is SKSpriteNode {
print(child.userData?.valueForKey("key") as? String)
//prints the value saved in the childs user data
if child.userData?.valueForKey("key") as? String == "100" {
print("It was a Success!")
}
if child.userData?.valueForKey("key") as? String == nil {
print("There was a problem :(")
}
}
我认为您的问题是 userData 开始时为 nil。试试这个...
func createSprite() {
let sprite = SKSpriteNode()
//init NSMutableDictionary
sprite.userData = NSMutableDictionary()
sprite.userData?.setValue("100", forKeyPath: "key")
frame.addChild(sprite)
}
希望对您有所帮助。