Sonic wasn't a villain, the writers weren't saying so, Snively was just being manipulative.
The whole time that Sonic was fighting Robotnik, Sniv was pledging his loyalty to the ruler of another country (and preparing to roll out the red carpet for her), helping ensure Robotnik would fall hard, and in general being a clever little traitor.