Search Unity

Question [Netcode] How to add a Network Behaviour component to a Network Object?

Discussion in 'Multiplayer' started by Reperadis, Apr 26, 2023.

  1. Reperadis

    Reperadis

    Joined:
    Apr 26, 2023
    Posts:
    1
    I need to add a component (derived from a NetworkBehaviour class) to a Network Prefab. I tried instantiating the prefab, adding the component and then spawning the prefab. As a result I see the prefab being spawned across the network but without the component and a with an error "Network Behaviour index 256 was out of bounds for (Network Object that spawned)" on the client side. On the server side everything works as intended (haven't tested whether the component works as a NetworkBehaviour component yet).
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,975
    Put the NetworkBehaviour on that prefab in the editor, then instantiate. You cannot add NetworkBehaviour components at runtime. If you need code that‘s different based on player etc. that behaviour has to be coded into the component.
     
  3. loransalabood

    loransalabood

    Joined:
    Feb 14, 2017
    Posts:
    2
    I am having hard time understanding the terminology here. a NetworkObject is literally a component that you can add to any game objects. NetworkBehaviour is class inherited from MonoBehaviour. So what do they actually mean when they say add NetworkBehaviour component to an object? it would be appreciate it if you can elaborate more on this.
     
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,975
    NetworkObject handles the networked state of the entire object. There must be only one per network prefab.

    NetworkBehaviour is a network-enabled MonoBehaviour. You can have several on a prefab, each handling individual networked aspects of the prefab like movement, shooting, inventory and what not. They can use NetworkVariables and register to receive network events. NetworkTransform is one of those specialized NetworkBehaviour components.