
[ad_1]
Hello everybody. There is a query. Let’s say I’ve some sort of state frequent to the entire scene.
- Where is it higher to connect the script? (you may’t appear so as to add to the scene itself)
- How do I get to this state from one other script (besides globalThis)
So principally what you need is a part that act like a singleton ?
I feel you may obtain it like this :
import { _decorator, Component } from "cc";
const { ccclass, executionOrder } = _decorator;
@ccclass("SingletonComponent")
@executionOrder(-1)
export class SingletonComponent extends Component {
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 "Do not connect a number of situations of SingletonComponent on the scene.";
}
}
}
As for the place to connect it, in case 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 very fact it’s a part although, a basic singleton that don’t extends something can be finest.
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 is advisable do is create a script in your belongings folder. So in my case I’m calling it globalVars and creating a couple of variables:
import { _decorator, Component } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('globalVars')
export class globalVars extends Component {
/* Global Variables */
public character;
public digital camera;
public begin = 0;
/* End Global Variables */
}
Then importing it to a different script like so (place at high of your script):
import { globalVars } from './globalVars';
You can 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;
}
Allowing you to do one thing like this from one other script:
globalVars.character.node.getPosition()
You will nonetheless have to create a script that’s linked to an object to import the script into however even making a node in your challenge will work for utilizing as a worldwide script for working issues at begin. Maybe name your node init or one thing.
Hopefully this helps.
Thanks
[ad_2]