从 UIViewController 打开 SKScene 时出现 NSInvalidArgumentException

NSInvalidArgumentException when opening SKScene from UIViewController

我正在创建我的第一个 SpriteKit 游戏,这是我正在尝试做的事情:

1.删除默认 Main_iphone 和 Main_ipad 故事板

2。在didFinishLaunchingWithOptions

下的AppDelegate.m中添加如下代码
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[CMViewController alloc] init];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    return YES;

3。在 viewController.m

中配置 SKScene
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    //Configure the view.
    SKView* skView = (SKView*)self.view;
    //Create and configure the scene.
    SKScene* scene = [CMHomeScene sceneWithSize:skView.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;
    //Present the scene.
    [skView presentScene:scene];
 }

运行时错误

-[UIView presentScene:]: unrecognized selector sent to instance 0x155854d0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView presentScene:]: unrecognized selector sent to instance 0x155854d0'
**** First throw call stack: (0x2c3eac1f 0x39b95c8b 0x2c3f0039 0x2c3edf57 0x2c31fdf8 0x10883d 0x2f8a7433 0x2f2cfa0d 0x2f2cb3e5 0x2f2cb26d 0x2f2cac51 0x2f2caa55 0x2fb0b1c5 0x2fb0bf6d 0x2fb16379 0x2fb0a387 0x32b770e9 0x2c3b139d 0x2c3b0661 0x2c3af19b 0x2c2fd211 0x2c2fd023 0x2f90e3ef 0x2f9091d1 0x10c2d1 0x3a115aaf) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

PS:

您已分配 SKView* skView = (SKView*)self.view。 我相信 self.view 不是 SKView 的子类,因此简单地进行类型转换会将您的 SKView 指向 UIView。

虽然构建代码会成功,但您肯定会遇到运行时错误,因为您的 SKView 会发现 self.view 将其真实身份 (UIView) 隐藏在空指针 SKView 后面。

您可能想要更改 3。将 View 配置为以下内容:

    - (void)viewWillLayoutSubviews 
    { 
    // Configure the view. 
    SKView* skView = [[SKView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    // Create and configure the scene. 
    SKScene* scene = [CMHomeScene sceneWithSize:skView.bounds.size]; 
    scene.scaleMode = SKSceneScaleModeAspectFill; 
    // Present the scene. 
    [skView presentScene:scene]; 
[self.view addSubview:skView];
    }

出现异常是因为您试图在 UIView 类型的视图上调用 presentScene,而方法属于 SKView.

故事板默认将 self.view class 设置为 SKView。由于您已删除故事板,并尝试按正常初始化方式使用控制器,因此 self.view 将作为 UIView 而不是 SKView.

启动

希望对您有所帮助。