It comes with practice. If you're adding basslines to written songs (where the chords & vocals are all in place), then listen to the song several times without playing any bass or even thinking of a bassline, then you'll start to hear a pattern from the music & the vocals that you can adapt on (usually the notes aren't there yet, if you know what I mean). You'll hear where can be synchronised & where parts could be changed for all the band & so forth.
A lot of the stuff I do works with the vocal line, either harmonising a melody or just reinforcing what is sung.
The more you write stuff the better you get at it, just like playing bass.