Fungi produce toxins as a defense mechanism or to outcompete other microorganisms. The production of these toxins can be influenced by environmental factors such as humidity, temperature, and the availability of nutrients. For instance, Aspergillus species produce aflatoxins when conditions are warm and moist.