OnClickDestroy.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="OnClickDestroy.cs" company="Exit Games GmbH">
  3. // Part of: Photon Unity Utilities
  4. // </copyright>
  5. // <summary>A compact script for prototyping.</summary>
  6. // <author>developer@exitgames.com</author>
  7. // --------------------------------------------------------------------------------------------------------------------
  8. namespace Photon.Pun.UtilityScripts
  9. {
  10. using System.Collections;
  11. using UnityEngine;
  12. using UnityEngine.EventSystems;
  13. /// <summary>
  14. /// Destroys the networked GameObject either by PhotonNetwork.Destroy or by sending an RPC which calls Object.Destroy().
  15. /// </summary>
  16. /// <remarks>
  17. /// Using an RPC to Destroy a GameObject is typically a bad idea.
  18. /// It allows any player to Destroy a GameObject and may cause errors.
  19. ///
  20. /// A client has to clean up the server's event-cache, which contains events for Instantiate and
  21. /// buffered RPCs related to the GO.
  22. ///
  23. /// A buffered RPC gets cleaned up when the sending player leaves the room, so players joining later
  24. /// won't get those buffered RPCs. This in turn, may mean they don't destroy the GO due to coming later.
  25. ///
  26. /// Vice versa, a GameObject Instantiate might get cleaned up when the creating player leaves a room.
  27. /// This way, the GameObject that a RPC targets might become lost.
  28. ///
  29. /// It makes sense to test those cases. Many are not breaking errors and you just have to be aware of them.
  30. ///
  31. ///
  32. /// Gets OnClick() calls by Unity's IPointerClickHandler. Needs a PhysicsRaycaster on the camera.
  33. /// See: https://docs.unity3d.com/ScriptReference/EventSystems.IPointerClickHandler.html
  34. /// </remarks>
  35. public class OnClickDestroy : MonoBehaviourPun, IPointerClickHandler
  36. {
  37. public PointerEventData.InputButton Button;
  38. public KeyCode ModifierKey;
  39. public bool DestroyByRpc;
  40. void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
  41. {
  42. if (!PhotonNetwork.InRoom || (this.ModifierKey != KeyCode.None && !Input.GetKey(this.ModifierKey)) || eventData.button != this.Button )
  43. {
  44. return;
  45. }
  46. if (this.DestroyByRpc)
  47. {
  48. this.photonView.RPC("DestroyRpc", RpcTarget.AllBuffered);
  49. }
  50. else
  51. {
  52. PhotonNetwork.Destroy(this.gameObject);
  53. }
  54. }
  55. [PunRPC]
  56. public IEnumerator DestroyRpc()
  57. {
  58. Destroy(this.gameObject);
  59. yield return 0; // if you allow 1 frame to pass, the object's OnDestroy() method gets called and cleans up references.
  60. }
  61. }
  62. }