I think it has to do with evolution of a few separate but linked traits:
- Inquisitiveness. We observe something and we want to know the reason behind it. This is beneficial because it leads to increase in knowledge, knowledge that can be practical for survival. However, there's always a "why" behind the "why", and our knowledge will always hit a dead end a the limits of our practical ability to detect the recursive underlying "why". If you are a parent of a young inquisitive child, you will understand this.
- Theory of Mind, our human ability to approximate the mental actions of another thinking being, and predict actions based on intentionality.
- Our intentionality detector.
- Survival drive. Our core operative is to stay alive. This drives most of our motivations, but at some point we all die. Our inherent survival drive doesn't mesh well with our inescapable mortality.
- Codifying game theory driven altruism. There is an evolutionarily benefit for having a certain rules for how to react to other thinking entities. Triggering reciprocal altruism, tit-for-tat strategy, revenge, sacrificing for family and tribe, all can be defined in evolutionary terms, in game theory strategies. By codifying these evolutionary derived strategies into laws, and then tying those laws to an infallible third party, it's possible to create a more efficient cultural strategy.
The first three combined to create our tendency to create the concept of a god.
The fourth motivates our concept of afterlife.
The fifth drives or attachment of morals to religion.
Examples:
So we see a dead body, and a guy running away. Our brain assess the evidence to determine if something was done intentionally. Did the body just drop dead, or was it killed, if it was killed, who was it killed by, why was it killed, does the killer pose a future threat to me based on our estimates of it's intentions?
This is a super useful tool set for survival. The individual that can best detect and predict intentionality, has a marked survival advantage in a world of thinking entities.
One test for intentionality, is when is you observe something that isn't easily explained by random actions of obvious natural causes.
You see a random rock, no intentionality.
You see a stack of rocks, intentionality.
So when you see highly structured and precise things, without easily observable mechanics behind them, it's natural to assign intention to them. Sun rising and falling, tides, seasons, moon cycles, earthquakes, volcanoes, stellar and planetary motion, etc. These all beg the expectation of intentionality behind them.
This leads to the idea of a gods, unseen, intentioned, movers of things.