Cocos 全局变量的使用

文件夹规范

在这里插入图片描述

Constants.ts 用于控制全局
GameScene:游戏入口文件
gameManager是控制全局的变量,讲入口文件赋值给它,这样其他组件引用Hello的时候,可以使用GameScene里的属性.
GameState是一个enum类型,其中每个值都是上一个值+1,用于控制游戏状态.
gameState表示当前游戏的状态.

import GameScene from "../../scripts/GameScene";

export enum GameState {
    READY = 1,
    PLAYING,
    PAUSE,
    OVER,
}


class Constants {
    private static _instance: Constants = null;
    constructor() {
        return Constants._instance;
    }
    public static get Instance(): Constants {
        return this._instance || new Constants()
    }
    public gameManager: GameScene = null;
    public gameState: GameState = GameState.READY;
}
let hello = Constants.Instance
export { hello as Constants }

在Player.ts里使用入口文件的函数:

const {ccclass, property} = cc._decorator;
import { Hello } from "./hello";


@ccclass
export default class Player extends cc.Component {
    onLoad(){
        Hello.gameManager.setNewCoin()
    }
}

GameScene.ts

// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { Hello } from "./hello";
import YellowBall from "./yellowball";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameScene extends cc.Component {
    @property(cc.Prefab)
    coinPrefab: cc.Prefab = null;

    @property(YellowBall)
    player: YellowBall = null;

    public starNode: cc.Node = null;

    setNewCoin() {
        let newCoin = cc.instantiate(this.coinPrefab);
        this.node.addChild(newCoin);
        newCoin.setPosition(this.getNewCoinPosition())
        newCoin.getComponent('YellowBall').GameScene = this;
        this.starNode = newCoin;
    }

    getNewCoinPosition() {
        let rand = Math.random() - 0.5;
        let randY;
        rand ? randY = -215 : randY = 215;
        return cc.v2(400, randY)
    }

    onLoad() {
        Hello.gameManager = this;
        this.setNewCoin();

    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>