[csharp] GrabbableObject.cs
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- using System.Collections;
- using UnityEngine;
- using System.Linq;
- using Photon.Pun;
- public abstract class GrabbableObject : MonoBehaviourPun
- {
- private bool isGrabbed;
- public bool IsGrabbed
- {
- private set
- {
- if (PhotonNetwork.IsMasterClient)
- {
- photonView.RPC(nameof(SetGrabbedState), RpcTarget.OthersBuffered, value);
- isGrabbed = value;
- }
- else
- {
- photonView.RPC(nameof(SetGrabbedState), RpcTarget.AllBuffered, value);
- }
- EnableCollision(!isGrabbed);
- }
- get => isGrabbed;
- }
- private Collider[] colliders;
- private Rigidbody[] rigidbodies;
- [SerializeField] private bool regainPhysics;
- // Start is called before the first frame update
- private void Awake()
- {
- colliders = GetComponentsInChildren<Collider>().Append(GetComponent<Collider>()).ToArray();
- rigidbodies = GetComponentsInChildren<Rigidbody>().Append(GetComponent<Rigidbody>()).ToArray();
- }
- public virtual GrabbableObject Grab(Transform newParent)
- {
- if (IsGrabbed) return null;
- IsGrabbed = true;
- transform.SetParent(newParent);
- StartCoroutine(RotateTowardsParent(newParent));
- return this;
- }
- private IEnumerator RotateTowardsParent(Transform parent)
- {
- float time = 0;
- float speed = 1f;
- Vector3 startPos = transform.position;
- Quaternion startRotation = transform.rotation;
- while (time < 1f)
- {
- transform.position = Vector3.Lerp(startPos, parent.position, time);
- transform.rotation = Quaternion.Slerp(startRotation, Quaternion.LookRotation(parent.forward), time);
- time += Time.fixedDeltaTime * speed;
- yield return new WaitForFixedUpdate();
- }
- }
- public virtual GrabbableObject Throw()
- {
- IsGrabbed = false;
- transform.SetParent(null);
- return null;
- }
- public abstract void Use(Vector3 direction);
- private void EnableCollision(bool enable)
- {
- foreach (var coll in colliders)
- {
- if (coll == null) continue;
- coll.enabled = enable;
- }
- foreach (var rb in rigidbodies)
- {
- if (rb == null) continue;
- rb.isKinematic = !enable;
- }
- }
- [PunRPC]
- private void SetGrabbedState(bool grabbed) => isGrabbed = grabbed;
- }
Editor
You can edit this paste and save as new: