Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Passing a Network Variable onto a parameter

Discussion in 'Netcode for GameObjects' started by Hakurei123, Jan 3, 2024.

  1. Hakurei123

    Hakurei123

    Joined:
    Nov 30, 2022
    Posts:
    5
    Newbie here, I just want to know if I can pass a variable to a method to change its value so that I wont have to create multiple methods for each Network Variable

    This is how I tried to do it:
    Code (CSharp):
    1.     [ServerRpc(RequireOwnership = false)]
    2.     private void ValueChange_ServerRpc(float NetVar, float newValue) {
    3.         NetVar = newValue;
    4.     }
    What am I doing wrong here?
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,621
    Writing nonsensical code. :p

    Both values are passed into the method by value. You assign one value to another. Nothing happens beside NetVar having the same value as newValue WITHIN the current method.

    To use NetworkVariable check the manual. You're supposed to assign to the Value property of an instance of NetworkVariable, it synchronizes automatically.
     
    Hakurei123 likes this.
  3. NoelStephens_Unity

    NoelStephens_Unity

    Unity Technologies

    Joined:
    Feb 12, 2022
    Posts:
    273
    Depending upon what you are trying to accomplish, you could also just use a struct that implements INetworkSerializable. This way you can set many properties (defined in your struct) at once and use that struct with an RPC or NetworkVariable (depending upon how you want the values to update and propagate).
     
    Hakurei123 likes this.
  4. Hakurei123

    Hakurei123

    Joined:
    Nov 30, 2022
    Posts:
    5
    I was under the impression that I can just do that since it wont let me use ref on a network variable... oh well, newbie mistake I guess.

    Im still in the process of learning C# and Unity so Im still a bit clueless when it comes to some of these things.