Cocos Creator中建设全局变量(TypeScript)

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


前言

刚入坑cocos 不知道数据往哪里存,百度找了一些经验帖都是js版,厚实表皮礼貌友好的问了几个大佬 给了我一个标准答案,扔网上给大伙分享分享。


正文

两种方法 选其一就行

我推荐用方法二 但我就是要写出来方法一

//变量文件
window["bianliang"]={
    name:0,
    age:'win',
    testFunction(){
        cc.log('这是一个函数')
    }
}

然后是 调用代码

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) {
        //每次触发点击事件就把age加20

        window['bianliang'].age =  window['bianliang'].age  + 20
        console.log(window['bianliang'].age);
        
    }
}

 接下来是方法2

//被调用端 存储端
class Test {
    public name = 'zhangsan';
    public age = 20;
    public audioArray = [1,2,3];
}
export let test: Test = new Test();

然后是 调用代码

import { test } from './data'//注意这里多了一个引用
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(touch: cc.Touch, event: cc.Event) {
        //直接调用
        test.age=test.age+20
        console.log(test);

    }

}

这个方法可能会正常一点 值得一提的是 需要在代码最上方加一条import去引用变量文件


总结

在Cocos Creator中,游戏数据可以存储在多个位置,最常见的位置包括:

  1. 资源目录(assets):该目录通常包含游戏中使用的所有图像、音频、视频等资源文件。这些文件可以通过资源管理器进行管理,并通过代码进行访问。

  2. 节点属性(Node Properties):节点属性是节点上存储的一些数据,例如位置、旋转、缩放等。可以使用代码来访问节点属性。

  3. 全局变量(Global Variables):可以使用全局变量来存储游戏中的全局数据,例如分数、生命值等。这些变量可以在代码中定义,并在整个游戏中进行访问。

有大佬的大腿抱真好。

猜你喜欢

转载自blog.csdn.net/m0_66016308/article/details/129282746
今日推荐