Cocos 全局变量的使用
生活随笔
收集整理的這篇文章主要介紹了
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.htmlimport { 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();}}
總結
以上是生活随笔為你收集整理的Cocos 全局变量的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 个性励志签名
- 下一篇: Cocos事件监听(JS)