# Pre-Play Validation

The Pre-Play Validation system automatically detects and resolves common configuration issues before simulation startup, reducing debugging time and ensuring reliable automation system behavior.

## Overview

Pre-Play Validation proactively identifies potential problems in your scene configuration and either automatically fixes them or provides clear guidance for resolution. This validation system catches issues early in the development process, preventing runtime failures and unexpected behavior during virtual commissioning.

Key benefits include:

* **Automated Problem Detection**: Identifies configuration conflicts before they cause runtime issues
* **Intelligent Auto-Fixes**: Automatically resolves common problems like conflicting component settings
* **Clear Diagnostic Messages**: Provides specific, actionable feedback for manual fixes
* **Development Workflow Integration**: Runs seamlessly during normal development activities
* **Reduced Debugging Time**: Catches issues before they become complex runtime problems

> **💡 Hint** Enable validation early in your project development to establish good configuration practices and catch issues as they develop rather than during final testing.

<figure><img src="/files/0GmodTOUjCFlwOulruWd" alt=""><figcaption><p>Enable Pre-Play Validation in RealvirtualController settings</p></figcaption></figure>

## Quick Start

### Enable Validation (1 minute)

1. **Locate RealvirtualController** in your scene (usually on a "Controller" GameObject)
2. **Check Validation Settings** in the Inspector:
   * **Validate Before Start**: ✅ Enable for pre-simulation checks
   * **Validation On Components Added**: ✅ Enable for real-time component validation
3. **Test the System**: Start Play mode and check Unity Console for validation messages

### Understanding Validation Output

Validation messages appear in Unity Console with this format:

```
[Validation] RuleName: Description of issue and action taken
Context: GameObject "ObjectName" → Component type
```

## Configuration Options

### RealvirtualController Settings

**Validate Before Start** Runs comprehensive scene validation when entering Play mode.

* **Type**: Boolean
* **Default**: true
* **Use case**: Catch configuration issues before simulation starts
* **Performance**: Minimal impact on startup time

**Validation On Components Added** Validates components immediately when added in Editor mode.

* **Type**: Boolean
* **Default**: true
* **Use case**: Prevent invalid configurations during scene building
* **Performance**: Real-time validation with no runtime impact

### Development Workflow Integration

**Recommended Settings for Different Phases**:

**Early Development**: Both validations enabled

* Helps establish proper configuration patterns
* Catches issues as components are added

**Production/Testing**: Pre-play validation enabled, component validation optional

* Ensures scene integrity before critical testing
* Reduces validation interruptions during rapid development

**Final Release**: Validation can be disabled for performance

* Remove validation overhead in final builds
* All configuration issues should be resolved by this stage

<figure><img src="/files/VVxxtSu6UpN0heG4zE2Y" alt=""><figcaption><p>Validation warnings displayed in Unity Console</p></figcaption></figure>

{% hint style="info" %}
**Best Practice**: Keep both validations enabled during development. The system is designed to be non-intrusive while providing valuable feedback for scene configuration quality.
{% endhint %}

## Validation Rules Reference

The validation system includes specialized rules that target common configuration problems in industrial automation setups.

### Control System Validation

#### BehaviorInterface Jogging Conflict Resolution

**Problem Detected**: Drive components with both BehaviorInterface control and manual jogging enabled

**Why This Matters**:

* BehaviorInterface components provide programmatic drive control for automation sequences
* Manual jogging controls (JogForward/JogBackward) are intended for manual testing and debugging
* Having both active creates conflicting control signals and unpredictable behavior

**Automatic Resolution**:

* Disables `JogForward` and `JogBackward` properties on affected Drive components
* Preserves BehaviorInterface control for proper automation operation
* Maintains drive functionality while eliminating control conflicts

**Example Scenario**:

```
Conveyor System with BehaviorInterfaceConveyor component:
✅ Before: Drive has jogging enabled + active BehaviorInterface
❌ Problem: Conflicting control signals cause erratic movement
✅ After: Jogging disabled, BehaviorInterface maintains full control
```

**Console Message**:

```
[Validation] BehaviorInterfaceJoggingRule: Disabled jogging on Drive. 
Active BehaviorInterface will control drive position and conflicts with manual jogging.
Context: GameObject "ConveyorDrive" → Drive component
```

#### Multiple BehaviorInterface Prevention

**Problem Detected**: GameObjects with multiple active BehaviorInterface components

**Why This Matters**:

* Each GameObject should have only one active control interface
* Multiple interfaces create ambiguous control authority
* Can cause timing conflicts and synchronization issues

**Automatic Resolution**:

* Keeps the first active BehaviorInterface component
* Disables additional BehaviorInterface components
* Preserves the primary control interface functionality

**Example Scenario**:

```
Robot Arm with multiple control interfaces:
✅ Before: BehaviorInterfaceRobot + BehaviorInterfaceSequence both active
❌ Problem: Conflicting position commands from two controllers
✅ After: Primary interface remains active, secondary disabled
```

### Motion System Validation

#### Single Drive Component Enforcement

**Problem Detected**: Multiple Drive components on the same GameObject

**Why This Matters**:

* Unity GameObjects support only one primary motion controller
* Multiple Drive components create conflicting transform updates
* Can cause jittery movement, position fighting, or complete motion failure

**Immediate Resolution**:

* Removes duplicate Drive components as soon as they're added
* Preserves the original Drive component configuration
* Triggers immediately during component addition (not just pre-play)

**Prevention Strategy**:

```
Hierarchy Design:
✅ Correct: One Drive per GameObject
  ├── ConveyorSystem (Drive component)
  ├── RobotArm (Drive component)
  └── ElevatorPlatform (Drive component)

❌ Incorrect: Multiple Drives on same GameObject
  ├── ComplexMachine (Drive + Drive) ← Second Drive removed
```

#### Transport Surface Hierarchy Validation

**Problem Detected**: Improper Drive-TransportSurface hierarchy configurations

**Critical Physics Requirements**:

* TransportSurface components need Drive control for proper operation
* Unity physics constraints prevent certain Drive-TransportSurface arrangements
* Missing Drive references cause non-functional conveyor systems

**Validation Logic**:

**✅ Valid Configurations**:

* TransportSurface with explicit DriveReference assigned
* TransportSurface with exactly one Drive in parent hierarchy
* TransportSurface as child of Drive GameObject

**❌ Invalid Configurations**:

* TransportSurface without Drive and no DriveReference
* TransportSurface with multiple Drives above it in hierarchy
* Drive component positioned above TransportSurface violating physics

**Practical Examples**:

```
✅ Correct Hierarchy 1: Direct Reference
Conveyor
├── Belt (TransportSurface + DriveReference to Drive)
└── Motor (Drive component)

✅ Correct Hierarchy 2: Parent-Child Relationship  
ConveyorSystem (Drive component)
└── Belt (TransportSurface component)

❌ Problematic Hierarchy: Missing Drive Control
Conveyor
└── Belt (TransportSurface only) ← No drive control

❌ Physics Violation: Drive Above TransportSurface
FactoryFloor (Drive component)
└── ConveyorSection (TransportSurface) ← Physics conflict
```

**Console Messages**:

```
[Validation] TransportSurfaceDriveHierarchyRule: TransportSurface requires a Drive component 
in the hierarchy to function properly. Please add a Drive component or assign DriveReference.
Context: GameObject "ConveyorBelt" → TransportSurface component
```

## Validation Triggers

### Pre-Play Validation

Automatically runs when entering Play mode (if enabled):

* **BehaviorInterface Jogging Conflicts**: Drive components with conflicting control methods
* **Multiple BehaviorInterface Detection**: GameObjects with multiple active interfaces
* **TransportSurface Hierarchy**: Drive-TransportSurface relationship validation

### Component Addition Validation

Runs immediately when components are added in Editor:

* **Multiple Drive Prevention**: Blocks duplicate Drive components on same GameObject

## Practical Usage Examples

### Common Development Scenarios

#### Scenario 1: Building a Conveyor System

**Step-by-step with Validation Feedback**:

1. **Create Conveyor GameObject**:

   ```
   Hierarchy: ConveyorSystem
   ```
2. **Add Drive Component**:

   ```
   ✓ Drive added successfully
   ```
3. **Add Second Drive (Mistake)**:

   ```
   ⚠ [Validation] PreventMultipleDrivesRule: Only one Drive component allowed per GameObject. 
      Removing duplicate Drive component.
   ✓ System prevents configuration error
   ```
4. **Add TransportSurface**:

   ```
   ConveyorSystem (Drive)
   └── Belt (TransportSurface)
   ✓ Hierarchy validated - proper Drive-TransportSurface relationship
   ```

#### Scenario 2: Robot Arm with Automation Control

**Development Progression**:

1. **Initial Setup**:

   ```
   RobotArm (Drive + manual jogging enabled)
   ✓ Manual testing configuration
   ```
2. **Add Automation Control**:

   ```
   RobotArm (Drive + BehaviorInterfaceRobot + jogging enabled)
   ⚠ [Validation] BehaviorInterfaceJoggingRule: Disabled jogging on Drive.
      Active BehaviorInterface will control drive position.
   ✓ System resolves control conflict automatically
   ```
3. **Final Configuration**:

   ```
   RobotArm (Drive + BehaviorInterfaceRobot)
   ✓ Ready for automated operation
   ```

### Manual Validation Control

#### Runtime Control

```csharp
// Dynamic validation control during development
public class ValidationController : MonoBehaviour
{
    public RealvirtualController realvirtualController;
    
    public void EnableValidation()
    {
        realvirtualController.ValidateBeforeStart = true;
        Debug.Log("Validation enabled for next Play mode start");
    }
    
    public void DisableValidationTemporarily()
    {
        realvirtualController.ValidateBeforeStart = false;
        Debug.Log("Validation temporarily disabled");
    }
    
    public void RunManualValidation()
    {
        if (realvirtualController != null)
        {
            realvirtualController.RunValidation();
        }
    }
}
```

#### Editor Integration

```csharp
// Custom editor integration for validation
[CustomEditor(typeof(RealvirtualController))]
public class RealvirtualControllerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Validation Tools", EditorStyles.boldLabel);
        
        if (GUILayout.Button("Run Validation Now"))
        {
            ((RealvirtualController)target).RunValidation();
        }
        
        if (GUILayout.Button("Reset Validation Settings"))
        {
            ((RealvirtualController)target).ValidateBeforeStart = true;
            ((RealvirtualController)target).ValidationOnComponentsAdded = true;
        }
    }
}
```

### Custom Validation Rules

#### Extending the Validation System

The validation system supports custom rules for project-specific requirements:

```csharp
// Custom validation rule example
public class CustomComponentValidationRule : PrePlayRule<CustomComponent>
{
    public override string RuleName => "CustomComponentValidationRule";
    
    protected override bool IsValid(CustomComponent component)
    {
        // Custom validation logic
        return component.RequiredReference != null;
    }
    
    protected override void FixComponent(CustomComponent component)
    {
        // Automatic fix if possible
        if (component.RequiredReference == null)
        {
            component.RequiredReference = component.GetComponent<RequiredType>();
        }
    }
    
    protected override string GetWarningMessage(CustomComponent component)
    {
        return "CustomComponent requires a valid reference for proper operation.";
    }
}
```

## Troubleshooting

### Validation Not Running

**Symptoms**: No validation messages appear in Unity Console when starting Play mode or adding components

**Diagnostic Steps**:

1. **Verify RealvirtualController Configuration**:

   ```csharp
   // Check controller setup
   var controller = FindObjectOfType<RealvirtualController>();
   if (controller == null)
   {
       Debug.LogError("RealvirtualController not found in scene");
   }
   else
   {
       Debug.Log($"Validation enabled: {controller.ValidateBeforeStart}");
   }
   ```
2. **Check Console Filter Settings**:
   * Ensure Unity Console shows "Info" level messages
   * Look for "\[Validation]" prefix in console messages
   * Check Console collapse setting doesn't hide validation messages
3. **Verify Component Targets**:
   * Validation only runs on components with active validation rules
   * Test with known validation scenarios (add second Drive component)

**Common Solutions**:

* Enable "Validate Before Start" in RealvirtualController Inspector
* Ensure RealvirtualController GameObject is active in scene
* Check that validation target components exist in scene

### Understanding Validation Messages

**Message Format Analysis**:

```
[Validation] RuleName: Action taken and reason
Context: GameObject "Name" → Component Type
```

**Example Interpretation**:

```
[Validation] BehaviorInterfaceJoggingRule: Disabled jogging on Drive.
Active BehaviorInterface will control drive position and conflicts with manual jogging.
Context: GameObject "ConveyorDrive" → Drive component

Translation:
- Rule: BehaviorInterface jogging conflict detection
- Action: Automatically disabled jogging properties
- Reason: Prevent control conflicts
- Location: ConveyorDrive GameObject's Drive component
```

### Validation Conflicts and False Positives

**When Validation Seems Wrong**:

1. **Understand the Rule Logic**:
   * Review rule documentation to understand why it triggered
   * Consider if your configuration follows realvirtual best practices
   * Check if special use case requires different approach
2. **Legitimate Special Cases**:

   ```csharp
   // Temporary validation disable for special configurations
   public class SpecialCaseController : MonoBehaviour
   {
       void Start()
       {
           var controller = FindObjectOfType<RealvirtualController>();
           if (controller != null)
           {
               // Disable for specific scenario
               controller.ValidateBeforeStart = false;
               Debug.Log("Validation disabled for special case scenario");
           }
       }
   }
   ```
3. **Configuration Review**:
   * Verify component hierarchy matches realvirtual patterns
   * Check component references and dependencies
   * Consider refactoring to standard configurations

### Performance and Integration Issues

**Editor Performance Impact**:

**Symptoms**: Noticeable delays when adding components or starting Play mode

**Optimization Approaches**:

* Disable component addition validation during rapid prototyping
* Use pre-play validation only for final testing phases
* Consider scene complexity and number of validation targets

**Multi-Scene Validation Issues**:

**Symptoms**: Validation inconsistencies across different scenes

**Solutions**:

* Ensure each scene has its own RealvirtualController
* Validate scene-specific component configurations
* Use prefabs for consistent validation setups across scenes

## See Also

* [RealvirtualController](https://github.com/game4automation/doc/blob/doc/components-and-scripts/basics/realvirtual-controller.md) - Main controller component configuration
* [Drive Component](/components-and-scripts/motion/drive.md) - Core motion component affected by validation
* [BehaviorInterface](https://github.com/game4automation/doc/blob/doc/components-and-scripts/behavior-interfaces/README.md) - Automation control components
* [TransportSurface](/components-and-scripts/motion/transportsurface.md) - Conveyor system components
* [Development Best Practices](https://github.com/game4automation/doc/blob/doc/components-and-scripts/advanced-topics/best-practices.md) - Scene configuration guidelines

***

© 2025 realvirtual GmbH [https://realvirtual.io](https://realvirtual.io/) - All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including printing, saving, photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.realvirtual.io/components-and-scripts/game4automation/pre-play-validation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
