Wednesday, September 7, 2022
HomeGame DevelopmentCommon entry to variables - Cocos Creator

Common entry to variables – Cocos Creator


Whats up everybody. There’s a query. Let’s say I’ve some type of state frequent to the entire scene.

  1. The place is it higher to connect the script? (you’ll be able to’t appear so as to add to the scene itself)
  2. How do I get to this state from one other script (besides globalThis)


So mainly what you need is a element that act like a singleton ?
I feel you’ll be able to obtain it like this :

import { _decorator, Part } from "cc";
const { ccclass, executionOrder } = _decorator;

@ccclass("SingletonComponent")
@executionOrder(-1)
export class SingletonComponent extends Part {
  personal static _instance: SingletonComponent;

  public static get occasion(): SingletonComponent {
    return this._instance;
  }

  protected onLoad(): void {
    if (SingletonComponent._instance == null) {
      SingletonComponent._instance = this;
    } else {
      throw "Don't connect a number of situations of SingletonComponent on the scene.";
    }
  }
}

As for the place to connect it, if you happen to want entry to it from a number of scenes, i’d recommend a presistent node : Loading and Switching Scenes · Cocos Creator

If you don’t make use of the very fact it’s a element although, a traditional singleton that don’t extends something could be finest.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments