As Mr M says, there are no rules you can always trust. However, since
un is a native English prefix, it is often used in words that don't derive from Latin, French or Greek.
In is common in loan words from those languages.
International phonetic laws that apply in many languages have changed in before certain sounds. It has become im before [m], [p ] and [b]. This is because when one produces these sounds, one's lips are closed and this makes pronouncing inmature more difficult than immature is. Therefore we say impolite, imbalance, not inpolite, inbalance.
For similar reasons in has often been assimilated before l and r:
illegal, irreligious, irresponsible
CB