Some offences have an element of intent, some do not.
There is a defence in common law called "honest mistake of fact" in which a person can be excused from otherwise criminal behaviour by virtue of really believing they were acting lawfully. The example given to me many years ago was of a person driving the wrong car out of a carpark because it looked exactly like their car (to a reasonable first approximation) and their key worked. Back in the old days of physical keys there weren't that many combinations so the chance of a matching key was higher than many might expect. Also, very old keys were known to be good at opening car doors.
Obviously, this defence does not work for all crimes.