using Unity.Netcode; using UnityEngine; namespace XRMultiplayer { /// /// Manages the targets in the target practice game. /// public class TargetManager : NetworkBehaviour { /// /// The targets in the game. /// public Target[] targets; /// /// The difficulty level of the game. /// protected NetworkVariable m_DifficultyLevel = new NetworkVariable(-1, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server); /// /// Indicates whether the targets are activated. /// protected bool m_activated = false; /// public virtual void Start() { // Subscribe to difficulty level change events m_DifficultyLevel.OnValueChanged += OnDifficultyChanged; // Deactivate all targets for (int i = 0; i < targets.Length; i++) { targets[i].gameObject.SetActive(false); } } /// public override void OnNetworkSpawn() { base.OnNetworkSpawn(); // If the difficulty level is already set, manually trigger the difficulty change event if (m_DifficultyLevel.Value != -1) { OnDifficultyChanged(-1, m_DifficultyLevel.Value); } } /// /// Activates the targets. /// public void ActivateTargets() { m_activated = true; // Set the difficulty level to 0 on the server if (IsServer) { m_DifficultyLevel.Value = 0; } } /// /// Deactivates the targets. /// public void DeactivateTargets() { m_activated = false; // Set the difficulty level to -1 on the server if (IsServer) { m_DifficultyLevel.Value = -1; } } /// /// Called when the difficulty level changes. /// /// The old difficulty level. /// The current difficulty level. void OnDifficultyChanged(int old, int current) { // Activate the target corresponding to the current difficulty level and enable it for (int i = 0; i < targets.Length; i++) { targets[i].gameObject.SetActive(current == i); if (current == i) { targets[i].EnableTarget(); } } } /// /// Sets the difficulty level on the server. /// /// The new difficulty level. public void ServerSetDifficulty(int newDifficulty) { m_DifficultyLevel.Value = newDifficulty; } /// /// Increases the difficulty level on the server. /// public void ServerIncreaseDifficulty() { m_DifficultyLevel.Value = (m_DifficultyLevel.Value + 1) % targets.Length; } /// /// Server RPC method called when a target is hit. /// /// The client ID of the player who hit the target. /// The color of the player who hit the target. [ServerRpc(RequireOwnership = false)] public void HitTargetServerRpc(ulong clientId, Color playerColor) { HitTargetClientRpc(clientId, playerColor); } /// /// Client RPC method called when a target is hit. /// /// The client ID of the player who hit the target. /// The color of the player who hit the target. [ClientRpc] public void HitTargetClientRpc(ulong clientId, Color playerColor) { // Call the TargetHitNetwork method on the target corresponding to the current difficulty level targets[Mathf.Clamp(m_DifficultyLevel.Value, 0, targets.Length - 1)].TargetHitNetwork(clientId, playerColor); } } }