日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Cocos 全局变量的使用

發布時間:2023/11/27 生活经验 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 全局变量的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。