PushBox.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using Mirror;
  6. public class PushBox : NetworkBehaviour
  7. {
  8. public int playersRequired;
  9. public Text numberTxt;
  10. public List<NetPlayer> DTP;
  11. public List<NetPlayer> Neighbours;
  12. public List<NetPlayer> targets;
  13. public List<NetPlayer> scannedList;
  14. void Start()
  15. {
  16. UpdateText();
  17. }
  18. void OnCollisionEnter2D(Collision2D col)
  19. {
  20. NetPlayer player = col.collider.GetComponent<NetPlayer>();
  21. if (player != null)
  22. {
  23. if (!DTP.Contains(player))
  24. {
  25. DTP.Add(player);
  26. UpdateNeighbourCount();
  27. }
  28. }
  29. }
  30. void OnCollisionExit2D(Collision2D col)
  31. {
  32. NetPlayer player = col.collider.GetComponent<NetPlayer>();
  33. if (player != null)
  34. {
  35. if (DTP.Contains(player))
  36. {
  37. DTP.Remove(player);
  38. UpdateNeighbourCount();
  39. }
  40. }
  41. }
  42. public void UpdateNeighbourCount()
  43. {
  44. targets = new List<NetPlayer>();
  45. Neighbours = new List<NetPlayer>();
  46. scannedList= new List<NetPlayer>();
  47. targets.AddRange(DTP);
  48. int failCount = 0;
  49. while(targets.Count > 0 && failCount < 50){
  50. failCount++;
  51. Neighbours.Add(targets[0]);
  52. scannedList.Add(targets[0]);
  53. foreach(NetPlayer neighbour in targets[0].touchingNeighbours){
  54. if(!scannedList.Contains(neighbour)){
  55. targets.Add(neighbour);
  56. }
  57. }
  58. scannedList.Add(targets[0]);
  59. targets.RemoveAt(0);
  60. }
  61. if(failCount >= 50){
  62. Debug.LogError("Fail switch triggered");
  63. }
  64. GetComponent<Rigidbody2D>().simulated=((playersRequired - Neighbours.Count) > 0);
  65. UpdateText();
  66. }
  67. void UpdateText()
  68. {
  69. numberTxt.text = (playersRequired - Neighbours.Count).ToString();
  70. }
  71. }