Universal access to variables

Hello everyone. There is a question. Let’s say I have some kind of state common to the whole scene.

  1. Where is it better to attach the script? (you can’t seem to add to the scene itself)
  2. How do I get to this state from another script (except globalThis)

So basically what you want is a component that act like a singleton ?
I think you can achieve it like this :

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

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

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

  protected onLoad(): void {
    if (SingletonComponent._instance == null) {
      SingletonComponent._instance = this;
    } else {
      throw "Do not attach multiple instances of SingletonComponent on the scene.";
    }
  }
}

As for where to attach it, if you need access to it from multiple scenes, i would suggest a presistent node : Loading and Switching Scenes · Cocos Creator

If you do not make use of the fact it is a component though, a classic singleton that do not extends anything would be best.

If you want to create global variables that can be accessed by any script so you can use it anywhere across your other scripts. All you need to do is create a script in your assets folder. So in my case I’m calling it globalVars and creating a few variables:

import { _decorator, Component } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('globalVars')
export class globalVars extends Component {
    
    /* Global Variables */

        public character;
        public camera;
        public start = 0;

    /* End Global Variables */ 
}

Then importing it to another script like so (place at top of your script):

import { globalVars } from './globalVars';

You can then call the variables like this:

globalVars.character

You can even do it with full objects by putting this into the variable on start:

   start() {
        globalVars.character = this;
    }

Allowing you to do something like this from another script:

globalVars.character.node.getPosition()

You will still need to create a script that is linked to an object to import the script into but even creating a node in your project will work for using as a global script for running things at start. Maybe call your node init or something.

Hopefully this helps.

Thanks

1 Like