1
0

Reward.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using UnityEngine;
  2. namespace Mirror.Examples.MultipleAdditiveScenes
  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. ClaimPrize(other.gameObject);
  19. }
  20. // This is called from PlayerController.CmdClaimPrize which is invoked by PlayerController.OnControllerColliderHit
  21. // This only runs on the server
  22. public void ClaimPrize(GameObject player)
  23. {
  24. if (available)
  25. {
  26. // This is a fast switch to prevent two players claiming the prize in a bang-bang close contest for it.
  27. // First hit turns it off, pending the object being destroyed a few frames later.
  28. available = false;
  29. Color32 color = randomColor.color;
  30. // calculate the points from the color ... lighter scores higher as the average approaches 255
  31. // UnityEngine.Color RGB values are float fractions of 255
  32. uint points = (uint)(((color.r) + (color.g) + (color.b)) / 3);
  33. // Debug.LogFormat(LogType.Log, "Scored {0} points R:{1} G:{2} B:{3}", points, color.r, color.g, color.b);
  34. // award the points via SyncVar on the PlayerController
  35. player.GetComponent<PlayerScore>().score += points;
  36. // spawn a replacement
  37. Spawner.SpawnReward(gameObject.scene);
  38. // destroy this one
  39. NetworkServer.Destroy(gameObject);
  40. }
  41. }
  42. }
  43. }