Cocos Creator在TypeScript中获取其他节点及组件

       控制台log输出为何频频失踪?
  wxss代码为何频频失效?
  wxml布局为何乱作一团?
  究竟是道德的沦丧?还是人性的缺失?
  让我们一起来 走 跑进科学


前言

记录一下别一会忘了又得上网搜 先看代码

在 Cocos Creator 中,要获取其他节点,可以使用 cc.find() 函数或 node.getChildByName() 方法。


正文

  • 使用 cc.find() 函数

cc.find() 函数可以通过节点路径查找节点。节点路径是指从场景根节点开始到目标节点的层级路径,用斜杠 / 分隔。

例如,假设场景中有一个根节点,名为 CanvasCanvas 下有一个名为 Player 的子节点,我们可以通过以下代码获取 Player 节点:

const playerNode = cc.find('Canvas/Player');
  • 使用 node.getChildByName() 方法

node.getChildByName() 方法可以通过子节点名称查找节点。

例如,假设场景中有一个根节点,名为 CanvasCanvas 下有一个名为 Player 的子节点,我们可以通过以下代码获取 Player 节点:

const canvasNode = cc.find('Canvas');
const playerNode = canvasNode.getChildByName('Player');

以上代码先通过 cc.find() 函数获取 Canvas 节点,然后通过 getChildByName() 方法获取 Player 节点。

示例 

需求为我点击瓶子1 瓶子1提起来 点击其他瓶子再把瓶子1归位

这里是路径图

代码是这样写的

import { common } from './common'
const { ccclass, property } = cc._decorator;

@ccclass
export default class tapBottle extends cc.Component {

    @property(cc.Node)
    bottle: cc.Node = null;


    onLoad() {
        this.bottle.on(cc.Node.EventType.TOUCH_START, this.tap, this)

    }
    tap(event: cc.Event) {
        console.log(this.name.substring(6, 7));
        let bottleindex = parseInt(this.name.substring(6, 7))


        console.log(common.select);
        //全部为零时true
        let status = common.select.every(item => item === 0)
        const index = common.select.indexOf(1);

        if (status) {
            common.select[bottleindex] = 1
            console.log('第一步');
            let move = cc.tween().by(0.1, { position: cc.v2(0, 20) })
            cc.tween(this.bottle).then(move).start();
        } else {
            let searchNode = cc.find(`Canvas/bottleGroup${index > 3 ? 1 : 0}/bottle${index}`); //通过全路径获取对应节点
            let scriptComponent = searchNode.getComponent('script'); //通过脚本类名Search获取组件
 
            let move = cc.tween().by(0.1, { position: cc.v2(0, -20) })
            cc.tween(searchNode).then(move).start();
            common.select = [0, 0, 0, 0, 0, 0, 0, 0, 0];
            console.log('第二步');
        }

    }

    start() {

    }

    // update (dt) {
    // }
}

其中并没有用到 getComponent 只获取到node就ok了;


总结

在实际开发中,我们可以根据场景的具体情况,选择使用 cc.find() 函数或 node.getChildByName() 方法来获取其他节点。

带伙们也试试吧

猜你喜欢

转载自blog.csdn.net/m0_66016308/article/details/129297901