Create global variables in Cocos Creator (TypeScript)

       Why does the console log output frequently disappear?
  Why does the wxss code fail frequently? Why is
  the wxml layout in a mess?   Is  it the loss 
  of morality?


foreword

I just entered cocos and I don't know where to store the data. Baidu found some experience posts, all of which are js versions. I asked a few big guys politely and friendly with thick skin and gave me a standard answer, and I threw it online to share with everyone.


text

Choose one of two methods

I recommend method two but I just want to write method one

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

and then the calling code

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);
        
    }
}

 Next is method 2

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

and then the calling code

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);

    }

}

This method may be normal. It is worth mentioning that you need to add an import at the top of the code to refer to the variable file


Summarize

In Cocos Creator, game data can be stored in multiple locations, the most common locations include:

  1. Resource directory (assets): This directory usually contains all image, audio, video and other resource files used in the game. These files can be managed through Explorer and accessed through code.

  2. Node Properties: Node properties are some data stored on the node, such as position, rotation, scaling, etc. You can use code to access node properties.

  3. Global Variables (Global Variables): Global variables can be used to store global data in the game, such as scores, life values, etc. These variables can be defined in code and accessed throughout the game.

It's nice to have a big guy's thigh hug.

Guess you like

Origin blog.csdn.net/m0_66016308/article/details/129282746