Reward.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using UnityEngine;
  2. namespace Mirror.Examples.MultipleAdditiveScenes
  3. {
  4. [RequireComponent(typeof(Common.RandomColor))]
  5. public class Reward : NetworkBehaviour
  6. {
  7. public bool available = true;
  8. public Common.RandomColor randomColor;
  9. protected override void OnValidate()
  10. {
  11. base.OnValidate();
  12. if (randomColor == null)
  13. randomColor = GetComponent<Common.RandomColor>();
  14. }
  15. [ServerCallback]
  16. void OnTriggerEnter(Collider other)
  17. {
  18. if (other.gameObject.CompareTag("Player"))
  19. ClaimPrize(other.gameObject);
  20. }
  21. [ServerCallback]
  22. 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. // award the points via SyncVar on the PlayerController
  34. player.GetComponent<PlayerScore>().score += points;
  35. // spawn a replacement
  36. Spawner.SpawnReward(gameObject.scene);
  37. // destroy this one
  38. NetworkServer.Destroy(gameObject);
  39. }
  40. }
  41. }
  42. }