More often than not, I have it happen while writing. The one that comes to mind first came early in a novel, a scene I was writing involving two young American Army soldiers in a rear area base in Vietnam, ca. 1969. They struck up an odd friendship after dark one night when one went out into an open area to smoke some weed, and ran into the other who had gone to the same place to observe the stars. As lights out drew near, they made their way back to their barracks, and this happened:
As they reached the dimly illuminated edge of the company clearing, Saint almost fell over the outstretched legs of a body.
I had no idea where that line came from. It wasn't part of my conception for the scene. It almost appeared on the page without my volition. I remember staring at it for a moment; I could either jettison it, or go with the flow. I did the latter:
He looked around, saw nothing else amiss, and leaned over to check the body. It was a soldier in jungle fatigues, lying on his front, head cradled in one arm so the face wasn't visible. One foot was booted, the other bare. Saint tugged at the nearest shoulder, to roll him over.
"Helen," the body moaned.
Now I had a character. I have no idea where that idea came from, either. But that little moment evolved into a major subplot that echoes and re-echoes through the rest of the novel, to have a significant effect on the conclusion.
It wasn't planned. It was in no outline, not even the rawest bullet-point kind of thing I tend to work with. All told, it probably generated ~12,000 words of the story, including three complete chapters.
This kind of thing is the major reason I urge people who ask questions about how to proceed when they think they're stuck, to "just write". Writing generates ideas. Epiphanies.
Oh, yeah. I needed a name for this new character. I called him 'Smith". That worked, too.
caw