Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question [MIRROR] Debugs in RPC working but not code

Discussion in 'Scripting' started by whoft, Jun 4, 2023.

  1. whoft

    whoft

    Joined:
    Jul 1, 2021
    Posts:
    17
    I have a system for object pooling networked boxes. When the object is pooled, the server takes control and places it out of bounds. Then, when necessary the server moves it into the world to be used. I'm running visual setup in a ClientRPC, and have debug messages telling me when the RPC is sent and received. However, none of the code inside the RPC is being executed on the client (except for the debugs). It works on the server. Where is my stupid mistake?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Mirror;
    5.  
    6. public class Barrel : NetworkBehaviour
    7. {
    8.     [Header("Base Stats")]
    9.     public bool health;
    10.     public Rigidbody rb;
    11.     public GameObject brokenBox;
    12.     public bool hasBroken;
    13.     public ParticleSystem spawnParticles;
    14.  
    15.     [Header("Explosives")]
    16.     public bool isExplosive;
    17.     public GameObject explosionParticles;
    18.     public float maxDamage;
    19.     public float minDamage;
    20.     public float knockback;
    21.     public float radius;
    22.     public float threshold;
    23.  
    24.     [Header("Caches")]
    25.     public Vector3 cachedVelocity;
    26.  
    27.     // Start is called before the first frame update
    28.     void Start()
    29.     {
    30.      
    31.     }
    32.  
    33.     // Update is called once per frame
    34.     void Update()
    35.     {
    36.         if(this.gameObject.GetComponent<PlayerHealth>().health < 0f && !hasBroken)
    37.         {
    38.             //Debug.Log("Broken lol");
    39.             hasBroken = true;
    40.  
    41.             Instantiate(brokenBox, transform.position, transform.rotation); //Possibly Random.rotation?
    42.  
    43.             if(isExplosive)
    44.             {
    45.                 //this.transform.root.gameObject.GetComponent<Barrel>().enabled = false;
    46.              
    47.                 Collider[] objectsInBlast = Physics.OverlapSphere(transform.position, radius);
    48.  
    49.                 foreach(Collider objectInBlast in objectsInBlast)
    50.                 {
    51.                     if(objectInBlast.GetComponent<PlayerHealth>() != null && objectInBlast.GetComponent<Barrel>() == null)
    52.                     {
    53.                         Vector3 distanceBetweenObjects = this.transform.position - Camera.main.transform.root.position;
    54.                         Vector3 directionBetweenObjects = distanceBetweenObjects/distanceBetweenObjects.magnitude;
    55.                         objectInBlast.GetComponent<PlayerHealth>().CmdHitFor(Mathf.Round(Mathf.Lerp(maxDamage, minDamage, Vector3.Distance(objectInBlast.transform.position, this.transform.position) / radius))); //Damage based off of distance
    56.                         objectInBlast.GetComponent<FPSController>().knockbackDirection = -directionBetweenObjects;
    57.                         objectInBlast.GetComponent<FPSController>().knockback = 0.25f;
    58.                     }
    59.              
    60.                     if(objectInBlast.GetComponent<Rigidbody>() != null)
    61.                     {
    62.                         objectInBlast.GetComponent<Rigidbody>().AddExplosionForce(knockback, transform.position, radius); //Add force
    63.                     }
    64.  
    65.                     if(objectInBlast.GetComponent<CameraShake>() != null)
    66.                     {
    67.                         objectInBlast.GetComponent<CameraShake>().shakeDuration = 0.1f;
    68.                     }
    69.  
    70.                     Camera.main.transform.root.gameObject.GetComponent<CameraShake>().shakeDuration = 0.1f;
    71.                 }
    72.  
    73.                 //this.transform.root.GetChild(0).rotation = Quaternion.Euler(new Vector3(-90f, 0, 0));
    74.                 GameObject particles = Instantiate(explosionParticles, transform.position, Quaternion.Euler(new Vector3(-90f, 0, 0)));
    75.                 //particles.transform.localScale = new Vector3(2.25f)
    76.                 //this.transform.root.GetChild(0).SetParent(null);
    77.             }
    78.  
    79.             Camera.main.transform.GetChild(1).GetComponent<PlayerGrabItem>()._grabableObject = null;
    80.  
    81.             this.gameObject.GetComponent<PlayerHealth>().CmdHitFor(-1 + this.gameObject.GetComponent<PlayerHealth>().health);
    82.          
    83.             StartCoroutine("ResetBox");
    84.         }
    85.     }
    86.  
    87.     void FixedUpdate()
    88.     {
    89.         if(rb.velocity.magnitude > 0.1f || rb.velocity.magnitude < -0.1f)
    90.         {
    91.             cachedVelocity = rb.velocity;
    92.         }
    93.     }
    94.  
    95.     void OnCollisionEnter(Collision coll)
    96.     {
    97.         Debug.Log("Collided");
    98.      
    99.         if(this.GetComponent<SpringJoint>() != null)
    100.         {
    101.             return;
    102.         }
    103.      
    104.         float velMagnitude = cachedVelocity.magnitude;
    105.      
    106.         if(velMagnitude > threshold && coll.collider.tag != "BrokenBox")
    107.         {
    108.             this.gameObject.GetComponent<PlayerHealth>().CmdHitFor(1);
    109.         }
    110.     }
    111.  
    112.     IEnumerator ResetBox()
    113.     {
    114.         this.gameObject.GetComponent<PlayerHealth>().CmdHitFor(-1 - this.gameObject.GetComponent<PlayerHealth>().health);
    115.      
    116.         foreach (Renderer renderer in transform.root.gameObject.GetComponentsInChildren(typeof(Renderer)))
    117.         {
    118.             renderer.enabled = false;
    119.         }
    120.  
    121.         rb.useGravity = false;
    122.         rb.constraints = RigidbodyConstraints.FreezePosition;
    123.         rb.freezeRotation = true;
    124.  
    125.         this.transform.position = new Vector3(0, 1000, 0);
    126.  
    127.         this.GetComponent<Collider>().tag = "PooledBox";
    128.  
    129.         CmdRemoveNetworkAuthority(this.gameObject.GetComponent<NetworkIdentity>());
    130.  
    131.         yield return null;
    132.     }
    133.  
    134.     [ClientRpc]
    135.     public void RpcSetBox()
    136.     {
    137.         Debug.Log("Recieved RPC");
    138.      
    139.         foreach (Renderer renderer in transform.root.gameObject.GetComponentsInChildren(typeof(Renderer)))
    140.         {
    141.             renderer.enabled = true;
    142.         }
    143.  
    144.         rb.useGravity = true;
    145.         rb.constraints = RigidbodyConstraints.None;
    146.         rb.freezeRotation = false;
    147.  
    148.         this.GetComponent<Collider>().tag = "Box";
    149.  
    150.         this.gameObject.GetComponent<PlayerHealth>().CmdHitFor(-1 + this.gameObject.GetComponent<PlayerHealth>().health);
    151.  
    152.         hasBroken = false;
    153.  
    154.         spawnParticles.Play();
    155.     }
    156.  
    157.     [Command(requiresAuthority = false)]
    158.     public void CmdRemoveNetworkAuthority(NetworkIdentity box)
    159.     {
    160.         box.RemoveClientAuthority();
    161.     }
    162. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Mirror;
    5.  
    6. public class BoxDispenser : NetworkBehaviour
    7. {
    8.  
    9.     public float timer;
    10.     public bool boxOccupied;
    11.     public GameObject explosiveBox;
    12.     public GameObject reinforcedBox;
    13.  
    14.     // Start is called before the first frame update
    15.     void Start()
    16.     {
    17.      
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if(!isServer) {return;}
    24.      
    25.         if(!boxOccupied)
    26.         {
    27.             timer -= Time.deltaTime;
    28.         }
    29.  
    30.         if(timer <= 0f)
    31.         {
    32.             RaycastHit hit;
    33.             Physics.Raycast(new Vector3(0, 1001, 0), new Vector3(0, -1, 0), out hit, 1.5f);
    34.  
    35.             if(hit.collider == null)
    36.             {
    37.                 return;
    38.             }
    39.  
    40.             hit.collider.gameObject.GetComponent<Barrel>().RpcSetBox();
    41.             Debug.Log("Sent RPC");
    42.             hit.collider.gameObject.transform.position = this.transform.position;
    43.             hit.collider.gameObject.transform.rotation = this.transform.rotation;
    44.             //hit.collider.gameObject.GetComponent<PlayerHealth>().CmdHitFor(-1 + this.gameObject.GetComponent<PlayerHealth>().health);
    45.          
    46.             timer = 5f;
    47.         }
    48.     }
    49.  
    50.     void OnTriggerStay(Collider collBox)
    51.     {
    52.         if(collBox.tag == "Box" || collBox.tag == "Player")
    53.         {
    54.             boxOccupied = true;
    55.         }
    56.     }
    57.  
    58.     void OnTriggerExit(Collider collBox)
    59.     {
    60.         boxOccupied = false;
    61.     }
    62. }
    63.  
    (Video of the phenomenon attached.)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Perhaps because you are early-outing when it isn't the server?

    Just a guess.

    Also, just for completeness: do you need all this horrible pooling noise in your project?

    The costs and issues associated with object pooling / pools:

    https://forum.unity.com/threads/object-pooling.1329729/#post-8405055

    https://forum.unity.com/threads/object-pooling-in-a-tower-defense-game.1076897/#post-6945089

    -------------------------------

    And in any case, debugging is debugging, network or regular:

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.