I have a situation where CC loses reference to certain objects - but only the second time I load a scene.
In this case I have flow like this Menu -> Select level -> Load level Level -> Back button -> Load Menu Menu -> Select level -> Load level and here the errors appears.
The script attached to the component doesn’t even know what this.node is.
I’ve ignored it until now but as release date creeps closer it’s something I’ll need to fix.
You can sort of fix it with using cc.find instead of using properties but it’s very cumbersome to work with.
But one serious issue is that I’m loading some JSON for building a list of buttons and even the JSON that I load is lost the second time I load the scene.
It looks like the class loses it’s scope the 2nd time it’s instantiated.
I did use cc.find, but it couldn’t find the button I need even though that button was visually appearing on the scene, and I still could interact with it just fine! This is the biggest thing I don’t understand about Cocos Creator at all.
Of course I did. I even double checked, triple checked it many times. I placed that code in onLoad(), the first time the scene was loaded, it can find just well. The second time it couldn’t find anything. It’s really weird.
The 1st time I didn’t play in the game scene at all. I went back to menu scene immediately after the game scene was loaded. If I played in the game scene at the 1st time, the 2nd time it will lost that reference!
try to cc.find on onEnable instead of onLoad? I can’t try it myself because I have that code in a previous commit. onEnable get’s triggered later than onLoad.
I’ve make a quick check again: the cc.find() works well in onLoad(). But as soon as I call the method which involves in processing that node the reference was lost.
Oh thank you so much! It works like a charm now. Your suggestion first didn’t work but I’ve figured out what has gone wrong. I have made an static _instance field for that class, but when the scene reloaded, the already set _instance somehow is different from the current this. I’ve set Manager._instance = this again in onLoad() and it works. Because this instance will be called from other objects that are instantiated at runtime.
FYI, I’m using static _instance extensively in this game.
When you load scene, everything under canvas would be released. Including components tied with nodes which are children of canvas. There several more ways to do it:
You would need to tie your static component to a node which is children of the persist node using addPersistRootNode().
Remove the node with the static component is tied to and cache is somewhere else before you do a scene switch, add the same node back to canvas once the new scene is loaded.