The main purpose is communication. like when you stub your toe , your nervous system communicates to your brain to react and have pain
Melanin provides pigmentation to the skin and it also provides UV ray protection (which is its role in the epidermis).