You have to learn seforim that enlighten your mind. It’s of utmost importance to learn seforim like Mesillas Yeshorim. You must learn the Rambam Hilchos Dei’os and Hilchos Teshuva, Sha’arei Teshuva d’Rabbeinu Yonah and Chovos Ha’levovos.
Seforim like that put so much into your mind that the truth is, like the Rambam says, once your mind is full of these valid, solid ideas then the wrong ideas won’t have place to come in.
But when there’s a vacuum in your head, your mind is empty, then the foolishness of the world comes into your head. The Rambam also says this with regards to immorality – ideas and thoughts of immorality can easily enter the mind when the mind is empty. But when your head is full of Torah ideas, its not so easy for wrong thoughts to enter your mind. ~ R’ Avigdor Miller zt”l