Universal access to variables

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