Saturday, September 10, 2022
HomeGame DevelopmentCommon entry to variables - Cocos Creator

Common entry to variables – Cocos Creator


Howdy everybody. There’s a query. Let’s say I’ve some form of state frequent to the entire scene.

  1. The place is it higher to connect the script? (you possibly can’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 principally what you need is a element that act like a singleton ?
I believe you possibly can obtain it like this :

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

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

  public static get occasion(): SingletonComponent {
    return SingletonComponent._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, when you want entry to it from a number of scenes, i might counsel a presistent node : Loading and Switching Scenes · Cocos Creator

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

If you wish to create world variables that may be accessed by any script so you should utilize it wherever throughout your different scripts. All it’s worthwhile to do is create a script in your property folder. So in my case I’m calling it globalVars and creating a number of variables:

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

@ccclass('globalVars')
export class globalVars extends Part {
    
    /* International Variables */

        public character;
        public digicam;
        public begin = 0;

    /* Finish International Variables */ 
}

Then importing it to a different script like so (place at prime of your script):

import { globalVars } from './globalVars';

You may then name the variables like this:

globalVars.character

You may even do it with full objects by placing this into the variable on begin:

   begin() {
        globalVars.character = this;
    }

Permitting you to do one thing like this from one other script:

globalVars.character.node.getPosition()

You’ll nonetheless have to create a script that’s linked to an object to import the script into however even making a node in your venture will work for utilizing as a world script for operating issues at begin. Perhaps name your node init or one thing.

Hopefully this helps.

Thanks

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments