You are probably right that this started as a lonely child. Children who are alone often create a rich fantasy life with imaginary friends to play with and even to help them solve problems. In that sense, it’s not a “horrible habit”. It’s an indicator of your personal strength, imaginationm and creativity that helped you cope with loneliness and helped you solve problems. Although not as common as in childhood, healthy adults can have imaginary friends too – either maintaining the “friends” they had in childhood or making up new friends and scenarios to solve problems.
The only problem I see is that you sometimes aren’t aware that you are doing it in public. I would need more information from you to give you good advice about how to compartmentalize your old problem-solvig skills and perhaps learn some new ones as well.
For that reason, I do suggest you see a therapist. I do not make this recommendation because I think you have a diagnosable mental illness. I do think a therapist could ask questions that would lead to helping you find ways to effectively self-monitor and increase your choices for how to manage stress.
I wish you well.