Search Unity

Third Party Unity Mirror Class with Interface

Discussion in 'Multiplayer' started by schuhbacca, Apr 12, 2021.

  1. schuhbacca

    schuhbacca

    Joined:
    Jul 29, 2020
    Posts:
    2
    Hello all,
    I was wondering if anyone has tried to do something like this before with Mirror. If not should there be another way I go about it. The jist is I have my player looking at some sort of item on screen. It is detected through a raycast. The item inherits from an Interactable interface. The error I am getting from Mirror (Weaver) is attached below.
    I think I may need a custom serializer if I want to do it this way, but maybe I should just avoid this approach in general? Would just be nice to be able to use an interface for all the interactable items.

    PlayerItemDetection
    Code (CSharp):
    1.  
    2.    void LookForInteractable()
    3.     {
    4.         // if we hit an interactable item
    5.        if (Physics.Raycast(this.transform.position + _rayCastOffset, transform.forward, out _hit, 4f, InteractLayer))
    6.         {
    7.             if (_controls.Player.Interact.ReadValue<float>() != 1) return;
    8.  
    9.             var interactable = _hit.collider.gameObject.GetComponent<IInteractable>();
    10.             if (interactable != null && interactable.CanInteract())
    11.             {
    12.                 CmdInteract(interactable);
    13.             }
    14.         }
    15.     }
    16.  
    17.     [Command]
    18.     void CmdInteract(IInteractbale i)
    19.     {
    20.         i.Interact();
    21.     }
    22.  
    Example Item
    Code (CSharp):
    1.  
    2. public class ItemController : NetworkBehaviour, IInteractable
    3. {
    4.      public void Interact(){
    5.           // Do something with the item
    6.      }
    7. }
    8.  
    9. public interface IInteractable {
    10.      void Interact();
    11. }
    12.  
    upload_2021-4-12_11-18-51.png