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.

RPC problem

Discussion in 'Multiplayer' started by AmazingRuss, Sep 18, 2008.

  1. AmazingRuss

    AmazingRuss

    Joined:
    May 25, 2008
    Posts:
    933
    I'm trying to call a static member function via rpc:
    Code (csharp):
    1.  
    2.  
    3. public class QNet : MonoBehaviour
    4. {
    5.   [RPC]
    6.   public static void SetSendRate(float sr)
    7.   {Network.sendRate = sr;}
    8.  
    9.   void FixedUpdate()
    10.   {
    11.     if(state == State.Hosting  prevSendRate != Network.sendRate)
    12.     {
    13.     prevSendRate = Network.sendRate;
    14.     networkView.RPC("QNet.SetSendRate", RPCMode.AllBuffered, Network.sendRate);        
    15.     }
    16.   }
    17.  
    18.  
    19. }

    But this complains that QNet sendrate does ont exist in any attached script. Any suggestions?
     
  2. jashan

    jashan

    Joined:
    Mar 9, 2007
    Posts:
    3,306
    I don't think calling a static RPC will work, since the RPCs are sent to a NetworkView (addressed by the NetworkViewID) which is a specific object. So, if you need the method to be static, you could have it called from within the RPC, something like:

    Code (csharp):
    1. public class QNet : MonoBehavior {
    2.     public static SetSendRate(float sr) { ... }
    3.  
    4.     [RPC()]
    5.     public void RPCSetSendRate(float sr) {
    6.         QNet.SetSendRate(sr);
    7.     }
    8. }
    9.  
    The QNet there is obviously optional (in particular as this is within QNet), but I think it's nice to add this there to make it obvious that this is a call to a static method (I also use this.Method and base.Method a lot because I think it makes the code more readable ... JavaScript fans might consider this insane ;-) ).

    If you need the possibility to call the method "statically", i.e. someone calls that method without knowing the object, and then it's distributed via the network, I'd recommend using a Singleton pattern instead of using static methods (there's a "special Unity singleton pattern" which doesn't construct objects because that doesn't work with MonoBehaviors).

    That would be the other way round then ;-)

    Sunny regards,
    Jashan
     
  3. AmazingRuss

    AmazingRuss

    Joined:
    May 25, 2008
    Posts:
    933
    Thank you, Jashan. I didn't need it to be static, but it didn't work the other way for some reason, and I figured a static method would be easier for the RPC to find.

    I took the static out and it works!