Canvas 中的脚本如何调用 component 的方法?

如下图 我在 lobbyCanvas 的脚本中定义 marquee 属性

接着 marquee compoent 上也有加上脚本

lobbyCanvas 跟 marquee 的腳本如下

// lobbyCanvas.js

cc.Class({
  extends: cc.Component,

  properties: {
    marquee: {
      default: null,
      type: cc.Label
    },

    memberInfo: {
      default: null,
      type: cc.Label
    }
  },

  onLoad: function () {
    console.log(this.marquee.moveAction)  // undefined
  }
})
// marquee.js

cc.Class({
  extends: cc.Component,

  properties: {
    width: {
      default: 300,
      type: cc.Integer
    },
    speed: {
      default: 0,
      type: cc.Integer
    }
  },

  onLoad: function () {
    this.node.runAction(this.moveAction(this.width, this.node.width))
  },

  moveAction: (width, length) => {
    return cc.repeatForever(
      cc.sequence(
        cc.moveTo(5, cc.p(-length)),
        cc.place(cc.p(0))
      )
    )
  }
}

想请教 如何在 lobbyCanvas 的脚本中,调用 marquee 实例的 moveAction 方法??

试了半天都试不出来

在lobbyCanvas的脚本里调用

this.marquee.node.getComponent(“marquee”).moveAction();

因为你在lobbyCanvas里引用了marquee这个cc.label类型的组件,所以this.marquee就是你的marquee组件(cc.label类型),然而你要调用的方法所在的自定义组件(你的JS脚本)又和marquee在同一个节点,所以就可以通过这个节点来获取你的自定义组件,获取到这个节点就是this.marquee.node,然后用这个节点获取到你的marquee组件,就是this.marquee.node.getComponent(“marquee”),获取到这个自定义组件再调用里面的方法就可以了,当然现在api优化过了,好像调用

this.marquee.getComponent(“marquee”).moveAction();

也是可以的

感谢~~ 原来关键是 getComponent 这个 方法:grinning:

:grin:不客气,getComponent就是一个node获取组件的方法,参数可以传组件名,也可以传组件的构造函数(比如:cc.Label)