Cannot reference other class inside Singleton class

import { _decorator, Component, Node } from 'cc';

import { B } from './B';

const { ccclass, property } = _decorator;

@ccclass('A')

export class A extends Component {

    start()

    {

        let tmp = B.instance.cClass.myNumber;

        console.log(tmp);

    }

}
import { _decorator, Component, Node } from 'cc';

import { C } from './C';

const { ccclass, property } = _decorator;

@ccclass('B')

export class B extends Component {

    private static _instance: B;

    public static get instance () {

        if (this._instance) {

            return this._instance;

        }

        this._instance = new B();

        return this._instance;

    }

    @property({type : C})

    public cClass : C = null;

}
import { _decorator, Component, Node } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('C')

export class C extends Component {

    public myNumber = 10;

}

I have A class, B singleton class, C class
A class will call B class via singleton instance, then call myNumber in C class.

Running the A class with output this error ’ [PreviewInEditor] Cannot read property ‘myNumber’ of null

I make sure that I have drag the C class into B singleton class in editor. I think i my understand something wrong about how singleton works in Typescript.

Have you tried using a decorator instead of importing it? Cocos Creator 3.8 Manual - Decorator

Hi, you can try make the class C a static class:

Export static class C extens component

Hi what does it mean? I dont understand. I thought i used property decorator. Can you provide an example based on my code ?

Hi, static class is not what I am trying to do (use minimal static and singleton class - singleton is also sort of a static class)
If I make C class static, there is no reason for B class as A can call C directly.
What I want is to have a singleton B class which can reference any other instanced class. And any other instanced class can reference each other through the bridge of singleton B class.
Yes I know I also can use event pattern. I just think it is weird that a simple pattern I showed above doesnt work as i thought it should.

I think the problem is " this._instance = new B(); ". because you grant value for instance with new B, that is not the instance in the current scene. you should try to change the singleton B to other class, not the subclass of component. then you grant the C component in the onLoad of C component, B.instance.cClass = this. (this mean C component)

it does work like the way you mention. But Im not sure if it is a good way. Lets try and profile later.