Search Unity

Resolved Playing AudioSources in ServerRpc Unity Netcode

Discussion in 'Netcode for GameObjects' started by YalnizCanavar, Jan 13, 2024.

  1. YalnizCanavar

    YalnizCanavar

    Joined:
    May 31, 2020
    Posts:
    10
    Hi, on unity netcode, i am trying to play audiosources but i cant figure out how to to play on server rpc's then sending with client rpc. How can we exactly play AudioSources ?
     
  2. Nyphur

    Nyphur

    Joined:
    Jan 29, 2016
    Posts:
    98
    Your post doesn't contain enough information to understand what your problem is. You can put whatever code you want inside a ClientRPC, play the audiosource the normal way.
     
  3. YalnizCanavar

    YalnizCanavar

    Joined:
    May 31, 2020
    Posts:
    10
    When i put audio source as paramater on Rpc methods it gives an error then i searched a bit and tried Inetworkserialize thing to serialize audio source and got another error says audio source is not serializeable, if i play a certain audio source without paramater it works normally, but i have to define which audio source should be played. If character is shooting it should play the shoot sound effect audio source then if character is throwing bomb it should play its audio source, i hope i explained well
    Thanks for your replies
     
  4. Nyphur

    Nyphur

    Joined:
    Jan 29, 2016
    Posts:
    98
    This is the wrong approach, an RPC can only send serialisable types and you should only be sending simple information such as ints, strings etc, you can't send references to complex types like audiosource. What you would normally do is create separate ShootingSoundClientRpc and BombingSoundClientRpc methods and inside that pick the correct audiosource to play. Or if you wanted to make a single generic PlaySoundClientRpc method you would send in an int indicating which sound effect to play (e.g. 0 for shoot, 1 for bomb). Could even make it an enum for ease.
     
  5. NoelStephens_Unity

    NoelStephens_Unity

    Unity Technologies

    Joined:
    Feb 12, 2022
    Posts:
    258
    Like nyphur was saying, you would want to associate your audio with something like an enum or perhaps an index in a list of audio files. You could create a ScriptableObject that holds references to your audio files and either assign them a unique enum or just use the index order of the audio references in the list.

    Then, when you want to play an audio file, you would send the enum or index of the audio file via RPC, get the audio reference from the scriptable object (whether references in the NetworkBehaviour or some global in-scene placed object), and play that audio file.
     
  6. YalnizCanavar

    YalnizCanavar

    Joined:
    May 31, 2020
    Posts:
    10
    Thanks Guys, i solved it by creating server and client rpc's for each audio source and for audiosource arrays i used int as paramater to define index of arrays
     
    NoelStephens_Unity likes this.