带有Skaction的动态名称
我的班级中定义了Skactions,例如:
let CSound = SKAction.playSoundFileNamed("C3.mp3", waitForCompletion: false)
let DSound = SKAction.playSoundFileNamed("D3.mp3", waitForCompletion: false)
我希望能够调用函数播放声音,我想动态地调整名称,如:
func playSound(noteName: String) {
print(noteName) // "C"
var name = noteName + "Sound"
print(name) // "CSound"
run(SKAction(named: name)!)
}
这会在run(skaction(命名)上造成致命错误:name)!)
行:
致命错误:未包装可选值
时出乎意料地发现了无效
为什么这是为什么?如何零?变量name
具有值csound
,并且该名称确实存在Skaction。如何使用这样的动态名称?
I have SKActions defined in my class, eg:
let CSound = SKAction.playSoundFileNamed("C3.mp3", waitForCompletion: false)
let DSound = SKAction.playSoundFileNamed("D3.mp3", waitForCompletion: false)
I want to be able to call a function to play sounds, and I want to adjust the name dynamically, like this:
func playSound(noteName: String) {
print(noteName) // "C"
var name = noteName + "Sound"
print(name) // "CSound"
run(SKAction(named: name)!)
}
This causes a fatal error on the run(SKAction(named: name)!)
line:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
Why is this? How is it nil? The variable name
has the value CSound
, and an SKAction does exist with that name. How can I use a dynamic name like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将声音存储在字典中:
如果有很多声音并且您不想重复
PlaysoundFileNamed
太多次,则可以执行map
:那么您可以像这样访问它:
skaction(nater> skaction(naty:)
从应用程序捆绑包中的一个.sks文件创建skaction
。您可以通过执行文件 - >新 - >文件...-> SpriteKit动作。您将文件名作为参数传递,并创建文件中编码的操作。You can store the sounds in a dictionary:
If there are many sounds and you don't want to repeat
playSoundFileNamed
too many times, you can do amap
:Then you can access it like this:
The
SKAction(named:)
creates anSKAction
from a .sks file in your app's bundle. You can add such a file in Xcode by doing File -> New -> File... -> SpriteKit Action. You pass in the file name as the parameter, and it creates the action encoded in the file.