Because different atoms have different electron structures with different energy levels.
The flame excites the electrons in the atom causing them to jump to a different quantum energy level. Then the electrons in the atom lose the extra energy as light. The wavelength of the light is determined by the quantum energy differences between the excited level and the new level.
Each atom has a unique energy spectrum because each atom has a unique electron structure. The electron structure determines the differences between the quantum energy levels. This causes each different type of atom to emit a unique spectrum of light in the flame test.
Helium was first identified by it 's spectrum as seen in the sun. Hence it name Helium meaning from the sun.