带有GKAgentDelegate的子类未调用agentDidUpdate

时间:2019-01-28 13:55:05

标签: ios swift scenekit

谁能告诉我,如果我在GameViewController中将委托设置为“ self”,为什么agentDidUpdate()起作用,但是当将委托设置为Player类时却没有,为什么这两个类都是GKAgentDelegate。该项目可以在这里下载-> https://drive.google.com/open?id=10l44gSKmhiYz21FDYEOKrWKU-y_ScCEL

GameViewController.swift

//This works
 func createPlayerAgent()
    {
        let p = Player()
        let agent = GKAgent3D()
        agent.delegate = self
        agent.behavior = GKBehavior()
        agentSystem.addComponent(agent)
    }
//This does not
 func createPlayerAgent()
    {
        let p = Player()
        let agent = GKAgent3D()
        agent.delegate = p
        agent.behavior = GKBehavior()
        agentSystem.addComponent(agent)
    }

@objc func renderer(_ renderer: SCNSceneRenderer,updateAtTime time: TimeInterval)
{
    print("renderer")
    // Calculate delta since last update and pass along to the agent system.
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = time;
    }

    let delta = time - self.lastUpdateTime
    self.lastUpdateTime = time;
    print(delta)
    self.agentSystem.update(deltaTime: delta)
}

@objc func agentDidUpdate(_ agent: GKAgent3D)
{
    print("agentDidUpdate")
}

Player.swift

import Foundation
import GameplayKit

class Player:NSObject , GKAgentDelegate
{

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init()
    {
        super.init()
    }

    @objc func agentDidUpdate(_ agent: GKAgent3D)
    {
        print("---agentDidUpdate")

    }

}

1 个答案:

答案 0 :(得分:2)

这是范围问题。功能启用后,p将不保存而被释放。

   {
    let p = Player()
    let agent = GKAgent3D()
    agent.delegate = p
  }

您必须保存p才能生存。