How to do singleton in Creator

Can someone show me how to use singleton in Creator.
I have a problem when i access to instance from other scripts it says it’s undefined but when it’s from base script it correctly works
my code :
var Controller = cc.Class({ extends: cc.Component, properties: { canvas: cc.Node, zoomTarget : cc.Node, moveTarget : cc.Node }, statics: { instance: null }, editor: { executionOrder: 100 }, onLoad : function () { Controller.instance=this; cc.log(Controller.instance); } });
other Script :
var Controller = require("Controller"); var MyNode = cc.Class({ extends: cc.Component, editor: { executionOrder: 200 }, properties: { baseScale: cc.Vec2, targetScale: cc.Vec2 }, start: function () { cc.log(Controller.instance); } });

Does this help:

1 Like

sorry i don’t find how to correctly get indentation

Thanks for the fast answer, i read it a bit but i dont get how should i apply this to cocos
Maybe if there is an exemple in cocos it could be great

Well i don’t find how to do it in cocos :confused:

I’ve found that the best way for managing cc.Component singletons is to create a preloader scene with all such components such as sound manager, custom loading screen for scene transitions, custom tooltip layer and such. This scene starts first, initializes all these managers and makes them persistent nodes, and only after that first game scene starts.
It is also extremely handy to predict heavy dynamic resources to load during this scene on web platform.

Also it would be good idea to have your singletons not as cc.Component inherited classes but as a global JS object where it is possilbe, e.g.:

var playerState = {
	level : 1,
	exp : 0,
	gold : 100,
	load : function() {},
	save : function() {},
};
module.exports = playerState;

and then somewhere else:

require("PlayerState").load()