Reward.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using UnityEngine;
  2. namespace Mirror.Examples.NetworkRoom
  3. {
  4. [RequireComponent(typeof(RandomColor))]
  5. public class Reward : NetworkBehaviour
  6. {
  7. public bool available = true;
  8. public RandomColor randomColor;
  9. void OnValidate()
  10. {
  11. if (randomColor == null)
  12. randomColor = GetComponent<RandomColor>();
  13. }
  14. [ServerCallback]
  15. void OnTriggerEnter(Collider other)
  16. {
  17. if (other.gameObject.CompareTag("Player"))
  18. {
  19. ClaimPrize(other.gameObject);
  20. }
  21. }
  22. // This is called from PlayerController.CmdClaimPrize which is invoked by PlayerController.OnControllerColliderHit
  23. // This only runs on the server
  24. public void ClaimPrize(GameObject player)
  25. {
  26. if (available)
  27. {
  28. // This is a fast switch to prevent two players claiming the prize in a bang-bang close contest for it.
  29. // First hit turns it off, pending the object being destroyed a few frames later.
  30. available = false;
  31. Color32 color = randomColor.color;
  32. // calculate the points from the color ... lighter scores higher as the average approaches 255
  33. // UnityEngine.Color RGB values are float fractions of 255
  34. uint points = (uint)(((color.r) + (color.g) + (color.b)) / 3);
  35. // Debug.LogFormat(LogType.Log, "Scored {0} points R:{1} G:{2} B:{3}", points, color.r, color.g, color.b);
  36. // award the points via SyncVar on the PlayerController
  37. player.GetComponent<PlayerScore>().score += points;
  38. // spawn a replacement
  39. Spawner.SpawnReward();
  40. // destroy this one
  41. NetworkServer.Destroy(gameObject);
  42. }
  43. }
  44. }
  45. }