🏰 System Overview
The Medieval NPC AI System is a comprehensive framework for creating realistic, personality-driven NPCs in medieval-themed Unity projects. The system integrates with the MedievalBioGenerator to provide rich character backgrounds and behaviors.
Key Features:
- Personality-driven behavior system with 12+ archetypes
- Dynamic behavior scoring based on schedule and context
- Medieval-specific traits and social roles
- Seamless integration with MedievalBioGenerator
- Role-based behaviors (children, adults, drunks)
- Schedule-driven NPC activities
System Components
NPCBehaviorProfile
Core Data Model
Stores personality traits, behavioral weights, and medieval-specific characteristics
NPCBehaviorProfileGenerator
Profile Creation
Generates behavior profiles based on archetypes and personality traits
MedievalBehaviorEngine
Behavior Execution
Executes AI behaviors based on profiles, schedules, and environmental context
MedievalNPCAIController
AI Control Interface
Main controller that coordinates between behavior engine and Unity components
🏗️ System Architecture
The Medieval NPC AI System follows a modular architecture designed for extensibility and performance:
// Architecture Overview
MedievalNPCAIController
├── NPCBehaviorProfile (Data Model)
├── MedievalBehaviorEngine (Behavior Logic)
├── NPCScheduleSystem (Time-based Activities)
└── Integration Layer (MedievalBioGenerator)
// Data Flow
1. MedievalBioGenerator → Character Data
2. NPCBehaviorProfileGenerator → Behavior Profile
3. MedievalBehaviorEngine → Behavior Execution
4. MedievalNPCAIController → Unity Integration
Performance Note: The system uses object pooling and efficient data structures to minimize garbage collection pressure. All behavior calculations are cached and updated only when necessary.
👤 NPC Behavior Profiles
The NPCBehaviorProfile class serves as the core data model for NPC personality and behavior. It encapsulates all traits, weights, and characteristics that drive NPC decision-making.
Core Properties
SocialRole
NPCSocialRole
Defines the NPC's role in society (Child, Adult, Drunk, etc.)
PrimaryArchetype
NPCPersonalityArchetype
Main personality archetype (Honest, Brave, Cheerful, etc.)
SecondaryArchetypes
List<NPCPersonalityArchetype>
Additional personality traits that modify behavior
CurrentMorality
float (0.0-1.0)
Current moral state, influences ethical decisions
CurrentSociability
float (0.0-1.0)
Current social engagement level
CurrentCourage
float (0.0-1.0)
Current courage level, affects risk-taking behavior
Behavioral Weights
BraveryWeight
float
Influence of bravery on decision-making
HonestyWeight
float
Influence of honesty on interactions
CheerfulnessWeight
float
Influence of cheerfulness on mood
EnergyWeight
float
Influence of energy on activity levels
DisciplineWeight
float
Influence of discipline on routine adherence
StealthSkill
float
Skill level in stealthy behavior
KnowledgeSeeking
float
Desire to learn and acquire knowledge
Medieval-Specific Traits
SuperstitionLevel
float
Belief in supernatural and omens
HonorCode
float
Adherence to personal and societal honor
FeudalLoyalty
float
Loyalty to feudal hierarchy
ReligiousPiety
float
Devotion to religious practices
FolkWisdom
float
Traditional knowledge and common sense
CraftsmanshipPride
float
Pride in skilled work and craftsmanship
FamilyDuty
float
Commitment to family obligations
CommunityResponsibility
float
Sense of duty to local community
Proud
float
Level of personal pride and dignity
Setter Methods (Encapsulation)
To maintain proper encapsulation while allowing external modification of private properties, the system provides setter methods:
public void SetSocialRole(NPCSocialRole role)
public void SetPrimaryArchetype(NPCPersonalityArchetype archetype)
public void SetSecondaryArchetypes(List<NPCPersonalityArchetype> archetypes)
public void SetCurrentMorality(float morality)
public void SetCurrentSociability(float sociability)
public void SetCurrentCourage(float courage)
🎭 Personality System
The personality system defines 12+ archetypes that drive NPC behavior. Each archetype influences different aspects of decision-making and interactions.
Personality Archetypes
None - No specific archetype
Honest - High morality, truthful behavior
Brave - High courage, risk-taking
Cheerful - High sociability, positive interactions
Energetic - High activity levels
Deceitful - Low morality, manipulative behavior
Cowardly - Low courage, avoidance behavior
Gloomy - Low sociability, negative mood
Lazy - Low energy, minimal activity
Courageous - Enhanced bravery variant
Trustworthy - High reliability and honesty
Compassionate - High empathy and helping behavior
Balanced - Moderate values across all traits
Personality Traits
Bravery - Courage in face of danger
Honesty - Truthfulness and integrity
Cheerfulness - Positive emotional state
Energy - Activity and vigor levels
Gloomy - Negative emotional state
Social Roles
Child - Young NPC with child-specific behaviors
Adult - Standard adult NPC behaviors
Drunk - Intoxicated NPC with altered behavior
Personality Generation: The NPCBehaviorProfileGenerator creates profiles by selecting a primary archetype and optional secondary archetypes, then setting appropriate trait weights and medieval-specific characteristics.
⚙️ Medieval Behavior Engine
The MedievalBehaviorEngine executes AI behaviors based on NPC profiles, schedules, and environmental context. It handles role-based behaviors and schedule-driven activities.
Core Behavior Methods
public void ExecuteBehavior(MedievalNPCAIController controller, NPCSchedulePeriod period)
Main entry point for behavior execution. Determines appropriate behavior based on schedule period and NPC profile.
private void ExecuteChildBehavior(MedievalNPCAIController controller, NPCSchedulePeriod period)
Handles child-specific behaviors including play, learning, and family interactions.
private void ExecuteAdultBehavior(MedievalNPCAIController controller, NPCSchedulePeriod period)
Manages adult behaviors including work, social interactions, and daily routines.
private void ExecuteDrunkBehavior(MedievalNPCAIController controller, NPCSchedulePeriod period)
Controls intoxicated NPC behaviors with altered movement and social patterns.
Schedule Periods
Dawn - Early morning activities
Morning - Work and daily preparation
Noon - Midday activities and meals
Afternoon - Continued work and social time
Evening - End of work, family time
Night - Rest and nighttime activities
Midnight - Deep night, minimal activity
Behavior Scoring System
The engine uses a sophisticated scoring system that considers:
- Personality weights (BraveryWeight, HonestyWeight, etc.)
- Current state values (CurrentMorality, CurrentSociability, CurrentCourage)
- Medieval-specific traits (HonorCode, ReligiousPiety, etc.)
- Schedule period and environmental factors
- Social role and archetype influences
// Example behavior scoring
float workScore = profile.EnergyWeight * 0.4f +
profile.DisciplineWeight * 0.3f +
profile.CurrentMorality * 0.2f +
profile.FamilyDuty * 0.1f;
float socialScore = profile.CheerfulnessWeight * 0.4f +
profile.CurrentSociability * 0.3f +
profile.CommunityResponsibility * 0.2f +
profile.ReligiousPiety * 0.1f;
🎮 AI Controller Integration
The MedievalNPCAIController serves as the main interface between the behavior engine and Unity's component system. It handles movement, interactions, and state management.
Key Integration Points
BehaviorProfile
NPCBehaviorProfile
Reference to the NPC's behavior profile
BehaviorEngine
MedievalBehaviorEngine
Reference to the behavior engine instance
CurrentSchedulePeriod
NPCSchedulePeriod
\
Current time period for behavior selection
Interaction Methods
public void StartConversation(MedievalNPCAIController otherNPC)
Initiates conversation with another NPC, considering personality compatibility and social context.
public void LookAt(Vector3 targetPosition)
Controls NPC gaze direction for social interactions and environmental awareness.
Conversation System
The conversation system considers:
- Personality compatibility between NPCs
- Social roles and hierarchy
- Current mood and sociability levels
- Medieval social norms and etiquette
Null Safety: All interaction methods include null checks to prevent runtime errors when GameObject references are invalid or components are missing.
📊 Data Models & Enums
The system uses comprehensive enums to define NPC characteristics, occupations, and behavioral states.
Family Traditions
None - No specific family tradition
Warrior - Military family background
Merchant - Trading family background
Crafter - Artisan family background
Farmer - Agricultural family background
Scholar - Academic family background
Blacksmithing - Metalworking tradition
Farming - Agricultural expertise
Trading - Commerce expertise
Soldiering - Military service
Crafting - General craftsmanship
Healing - Medical knowledge
Scholarship - Academic pursuits
Thievery - Criminal background
Nobility - Aristocratic lineage
Priesthood - Religious vocation
Occupations
None - No specific occupation
Artisan - Skilled craftsperson
Peasant - Agricultural worker
Farmer - Agricultural specialist
Fisher - Fishing specialist
Hunter - Hunting specialist
Shepherd - Livestock caretaker
Laborer - General worker
Herder - Animal husbandry
Blacksmith - Metalworker
Carpenter - Woodworker
Mason - Stone worker
Miner - Mining specialist
Baker - Bread maker
Brewer - Alcohol producer
Guard - Security personnel
Soldier - Military personnel
Merchant - Trader
Trader - Commerce specialist
Healer - Medical practitioner
Scholar - Academic
Clerk - Administrative worker
Noble - Aristocrat
Knight - Military noble
Priest - Religious leader
Monk - Religious devotee
Nun - Female religious devotee
Innkeeper - Hospitality provider
Tailor - Clothing maker
Tanner - Leather worker
Potter - Ceramics maker
Bard - Entertainer and storyteller
Entertainer - Performance artist
Beggar - Destitute person
Thief - Criminal
Bandit - Armed criminal
Ranger - Wilderness specialist
Raider - Military criminal
Scout - Reconnaissance specialist
Cutthroat - Violent criminal
Poacher - Illegal hunter
Veteran - Experienced soldier
Elder - Respected senior
Child - Young person
Criminal Backgrounds
None - No criminal history
Petty - Minor offenses
Theft - Stealing-related crimes
Violent - Physical crimes
Political - Crimes against authority
🔗 Integration Guide
This section provides practical guidance for integrating the Medieval NPC AI System with your Unity project.
Basic Setup
// 1. Add MedievalNPCAIController to your NPC GameObject
public class MyNPC : MonoBehaviour
{
private MedievalNPCAIController aiController;
void Start()
{
aiController = GetComponent<MedievalNPCAIController>();
// 2. Generate or assign behavior profile
var profileGenerator = new NPCBehaviorProfileGenerator();
var profile = profileGenerator.GenerateProfile(NPCPersonalityArchetype.Honest);
aiController.BehaviorProfile = profile;
}
}
MedievalBioGenerator Integration
// Integrate with MedievalBioGenerator character data
public void IntegrateWithBioGenerator(CharacterBio characterBio)
{
var profile = new NPCBehaviorProfile();
// Map bio data to behavior profile
profile.SetPrimaryArchetype(MapBioToArchetype(characterBio.Personality));
profile.Occupation = characterBio.Occupation;
profile.FamilyTradition = characterBio.FamilyBackground;
// Set medieval-specific traits based on bio
profile.ReligiousPiety = characterBio.ReligiousDevotion * 0.01f;
profile.HonorCode = characterBio.SocialStanding * 0.01f;
aiController.BehaviorProfile = profile;
}
Schedule Integration
// Update behavior based on time of day
void Update()
{
var currentTime = GameTimeManager.GetCurrentTime();
var schedulePeriod = GetSchedulePeriod(currentTime);
aiController.CurrentSchedulePeriod = schedulePeriod;
aiController.BehaviorEngine.ExecuteBehavior(aiController, schedulePeriod);
}
Integration Tip: The system is designed to work seamlessly with existing Unity components. Simply add the MedievalNPCAIController to any GameObject and configure the behavior profile to start using the AI system.
💡 Best Practices
Performance Optimization
- Cache Component References: Store references to frequently accessed components in Awake() or Start()
- Use Object Pooling: Pool NPC objects to minimize instantiation overhead
- Limit Update Frequency: Update AI behaviors at reasonable intervals (0.5-2 seconds) rather than every frame
- Profile-Based Optimization: Use simpler behaviors for background NPCs
Design Guidelines
- Maintain Consistency: Ensure personality traits align with medieval social norms
- Balance Complexity: Start with primary archetypes before adding secondary traits
- Test Interactions: Verify NPC interactions work correctly with different personality combinations
- Monitor Performance: Use Unity Profiler to identify bottlenecks in behavior calculations
Debugging Tips
- Use Gizmos: Visualize NPC behavior states and decision points
- Log Key Decisions: Log important behavior choices for debugging
- Test Edge Cases: Verify behavior with extreme personality values
- Validate Integration: Ensure MedievalBioGenerator data maps correctly to behavior profiles
Common Pitfalls:
- Forgetting to set the CurrentSchedulePeriod before calling ExecuteBehavior
- Not checking for null references in interaction methods
- Using direct property assignment instead of setter methods for private properties
- Overlooking the need to add missing enum values when extending the system
📚 Related Documentation
For more detailed information about specific components of the Medieval NPC AI System, please refer to the dedicated documentation pages:
📋 Behavior Profiles Documentation
Detailed information about:
- Personality archetypes and trait weighting systems
- Profile generation methods and customization options
- Runtime profile modification and dynamic personality changes
- Complete AI Controller integration workflow
- MedievalBioGenerator integration and profile assignment
⚙️ Behavior Engine Documentation
Comprehensive coverage of:
- Schedule management and time-based behavior systems
- Role-based behaviors for different medieval social classes
- Social interaction systems and conversation mechanics
- Environmental factors including weather and seasonal effects
- Advanced behavior patterns and debugging tools
📅 Documentation Last Updated: November 25, 2025
Medieval NPC AI System - Comprehensive Unity Framework for Medieval Character AI