Skip to content

Release/unity 6 #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

InboraStudio
Copy link

ECS Network Racing Sample - Improvements & Documentation

This document provides a comprehensive overview of the improvements made to the ECS Network Racing Sample project, including bug fixes and new features.

Table of Contents

  1. Bug Fixes
  2. Debug Logging System
  3. Getting Started
  4. Additional Resources

Bug Fixes

1. Vehicle Velocity Threshold Configurable

File: Assets/Scripts/Gameplay/Vehicle/VehicleControlSystems.cs and Assets/Scripts/Components/Wheel.cs

Issue:
The WheelRaycastJob contained a hardcoded velocity check that would skip raycast operations if the velocity exceeded 50 units. This value was arbitrary and not configurable, which could cause unexpected behavior at high speeds for different vehicle types.

Fix:

  • Added a MaxSafeVelocity property to the Wheel component
  • Added a configurable field in the VehicleAuthoring class with a default value of 50f
  • Updated the raycast job to use this configurable value instead of the hardcoded one

Benefits:

  • Allows fine-tuning of physics behavior per vehicle type
  • Makes the velocity limit clearly visible in the Unity Inspector
  • Improves code clarity by removing magic numbers

2. Suspension Physics Bug Fixed

File: Assets/Scripts/Gameplay/Vehicle/VehicleControlSystems.cs

Issue:
In the SuspensionForceJob, there was an incorrect use of math.clamp with parameters in the wrong order. The function was called with math.clamp(10, -10, springVelocity) which had min greater than max, causing incorrect clamping behavior of spring velocity.

Fix:

  • Corrected the parameter order to math.clamp(springVelocity, -10, 10)
  • Improved the comment to better explain the purpose of the clamping

Benefits:

  • Fixed potential unpredictable physics behavior
  • Ensures suspension forces are properly calculated
  • Improved code readability with clearer comments

3. Network Connection Error Handling

File: Assets/Scripts/Gameplay/Connection/ServerConnectionUtils.cs

Issue:
The network connection code lacked proper error handling for invalid IP addresses or failed connections. Additionally, the DestroyLocalSimulationWorld method could potentially cause issues by disposing of worlds without checking if it was safe to do so.

Fix:

  • Added IP address validation before attempting connection
  • Added try-catch blocks around network operations
  • Added a LastConnectionError string to store error messages
  • Replaced DestroyLocalSimulationWorld with a safer SafeDestroyLocalSimulationWorld method that includes exception handling
  • Added check for world.IsCreated before disposing

Benefits:

  • More robust error handling prevents crashes
  • Users get meaningful error messages
  • World disposal is safer and prevents memory leaks or exceptions
  • Added mechanism to display connection errors to the user

4. Input Handling Improvement

File: Assets/Scripts/Gameplay/Vehicle/VehicleInputSystem.cs

Issue:
The CarInputSystem was adding inputs from multiple sources together, which could lead to unintended magnitudes if multiple input methods were active simultaneously. This made vehicle control unpredictable when using multiple input devices.

Fix:

  • Changed from adding input values to selecting the maximum absolute value
  • Added a helper method UpdateMaxAbsoluteValue to simplify this process
  • Improved code structure with better comments and semantic naming

Benefits:

  • More predictable and consistent vehicle control
  • Better handling of multiple input devices
  • Improved code readability and maintainability

5. Configurable Network Smoothing

File: Assets/Scripts/Gameplay/Vehicle/VehicleSmoothingSystem.cs

Issue:
The VehicleSmoothingSystem used a hardcoded smoothing factor of 0.7f for all smoothing operations. This value wasn't configurable and might not be optimal for all network conditions or game feel requirements.

Fix:

  • Added a new SmoothingConfig component to store smoothing parameters
  • Created a constant for the default smoothing value
  • Updated all smoothing methods to use the configurable smoothing factor
  • Made the system obtain the value from the component at runtime

Benefits:

  • Allows tuning of network smoothing behavior without code changes
  • Can adapt to different network conditions or player preferences
  • Makes the system more maintainable and modular

6. SystemAPI Access in Burst-Compiled Methods

File: Assets/Scripts/Gameplay/Vehicle/VehicleSmoothingSystem.cs

Issue:
The system was trying to use GetComponentLookup inside Burst-compiled methods without having a reference to the SystemState, causing a SGSG0002 compiler error.

Fix:

  • Added a SharedStatic<float> field to store the smoothing factor
  • Added an OnUpdate method to update this static value from the component data
  • Modified the Burst-compiled smoothing methods to use the shared static value instead of trying to access component data directly

Benefits:

  • Fixed the compiler error
  • Improved performance by avoiding component lookups in the smoothing methods
  • Made the code more robust and compatible with Burst compilation

7. C# Language Version Compatibility

File: Assets/Scripts/Gameplay/Vehicle/VehicleSmoothingSystem.cs

Issue:
The code was using a parameterless struct constructor which is only available in C# 10.0 or later, but the project is using C# 9.0, causing a CS8773 compiler error.

Fix:

  • Removed the parameterless struct constructor
  • Initialized the struct with object initialization syntax in the OnCreate method

Benefits:

  • Fixed the compiler error
  • Made the code compatible with C# 9.0
  • Maintained the same functionality with a different initialization approach

8. Vivox Service Null Reference Exception

File: Assets/Scripts/Gameplay/UI/Vivox/MonoBehaviours/VivoxChannel.cs

Issue:
The OnDestroy method in VivoxChannel was attempting to unsubscribe from VivoxService.Instance events without checking if the instance was null. Additionally, it was not unsubscribing from the LoggedOut event that was subscribed to in the JoinLobbyChannel method.

Fix:

  • Added a null check for VivoxService.Instance before unsubscribing from events
  • Added unsubscription for the LoggedOut event that was missing
  • Improved code safety for object cleanup during scene transitions

Benefits:

  • Prevents NullReferenceException when destroying VivoxChannel objects
  • Ensures proper cleanup of all event subscriptions
  • Handles the case where VivoxService might already be destroyed

Debug Logging System

A comprehensive debug and logging system for the ECS Network Racing Sample that provides:

  • Color-coded console logs for different types of events
  • Tracking of game state transitions
  • Logging of player actions
  • Network event logging
  • Easy integration with existing systems

Getting Started

  1. Add the RaceLoggerSetup component to a GameObject in your main scene
  2. Create a RaceLoggerSettings asset by right-clicking in the Project view and selecting Create > Racing > Debug > Logger Settings
  3. Assign the settings asset to the RaceLoggerSetup component

Log Types

The logging system supports different types of logs with distinct colors:

  • Info (Cyan): General information messages
  • Success (Green): Successful operations and achievements
  • Warning (Yellow): Potential issues or noteworthy events
  • Error (Red): Error conditions
  • Gameplay (Magenta): Game state and gameplay events
  • Network (Blue): Networking and connection events
  • Physics (Teal): Physics-related events

Usage Examples

Basic Logging

// Log an informational message (cyan)
RaceLogger.Info("Game initialized");

// Log a success message (green)
RaceLogger.Success("Player connected successfully");

// Log a warning (yellow)
RaceLogger.Warning("Performance may be affected");

// Log an error (red)
RaceLogger.Error("Failed to load asset");

// Log a gameplay event (magenta)
RaceLogger.Gameplay("Player entered finish line");

// Log a network event (blue)
RaceLogger.Network("Connected to server: 192.168.1.1");

// Log a physics event (teal)
RaceLogger.Physics("Collision detected");

Log Sections

To group related logs, you can create labeled sections:

RaceLogger.LogSection("RACE STARTED");

Custom Colored Logs

You can use custom colors by specifying a hex color:

RaceLogger.CustomColor("Special event occurred", "#FF00FF");

Configuration

The RaceLoggerSettings asset allows you to configure:

  • Enable/disable all logging
  • Control which categories of logs are shown
  • Configure advanced features like stack traces for errors

Architecture

Core Components

  1. RaceLogger: Static utility class with methods for different types of logs
  2. RaceLoggerManager: Singleton manager that initializes the logging system
  3. RaceLoggerSettings: ScriptableObject for configuration
  4. RaceStateLoggerSystem: ECS system that tracks race state changes
  5. RaceLoggerSetup: MonoBehaviour for easy setup in scenes

Integration Points

The logging system integrates with:

  • Race State System: Logs state transitions during races
  • Car Selection UI: Logs player car selections
  • ServerConnectionUtils: Logs network connections and errors

Additional Features

  • Automatic initialization logging with system info
  • Detailed state transition tracking
  • Network error logging

Customization

You can extend the system by:

  1. Adding new log types to RaceLogger
  2. Creating new integration points with other systems
  3. Modifying the RaceLoggerSettings to include additional options

Summary

These improvements address several core issues in the ECS Network Racing Sample, making it more robust, configurable, and maintainable. The focus has been on:

  1. Making hardcoded values configurable
  2. Fixing incorrect physics calculations
  3. Improving error handling in networking code
  4. Enhancing input processing for multiple devices
  5. Making network smoothing more adaptable
  6. Ensuring compatibility with Burst compilation
  7. Maintaining compatibility with C# 9.0
  8. Fixing null reference exceptions in third-party integrations
  9. Adding a comprehensive debug logging system

All changes were made with backward compatibility in mind and should integrate seamlessly with the existing codebase.

@InboraStudio
Copy link
Author

Thank you ❤️ it takes me 9 days to Complete.

@InboraStudio
Copy link
Author

Hello sir can you please Review it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant