question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NetworkList - UnityException: EditorPrefsGetInt is not allowed to be called

See original GitHub issue

Describe the bug

UnityException: EditorPrefsGetInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'Bag' on game object 'Player'.
See "Script Serialization" page in the Unity Manual for further details.
Unity.Collections.NativeLeakDetection.Initialize () (at /Users/bokken/buildslave/unity/build/Runtime/Export/NativeArray/DisposeSentinel.cs:28)
Unity.Collections.NativeLeakDetection.get_Mode () (at /Users/bokken/buildslave/unity/build/Runtime/Export/NativeArray/DisposeSentinel.cs:41)
Unity.Collections.LowLevel.Unsafe.DisposeSentinel.CreateInternal (Unity.Collections.LowLevel.Unsafe.DisposeSentinel& sentinel, System.Int32 callSiteStackDepth) (at /Users/bokken/buildslave/unity/build/Runtime/Export/NativeArray/DisposeSentinel.cs:107)
Unity.Collections.LowLevel.Unsafe.DisposeSentinel.Create (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle& safety, Unity.Collections.LowLevel.Unsafe.DisposeSentinel& sentinel, System.Int32 callSiteStackDepth, Unity.Collections.Allocator allocator) (at /Users/bokken/buildslave/unity/build/Runtime/Export/NativeArray/DisposeSentinel.cs:101)
Unity.Collections.NativeList`1[T].Initialize[U] (System.Int32 initialCapacity, U& allocator, System.Int32 disposeSentinelStackDepth) (at Library/PackageCache/com.unity.collections@1.0.0-pre.5/Unity.Collections/NativeList.cs:141)
Unity.Collections.NativeList`1[T]..ctor (System.Int32 initialCapacity, Unity.Collections.AllocatorManager+AllocatorHandle allocator, System.Int32 disposeSentinelStackDepth) (at Library/PackageCache/com.unity.collections@1.0.0-pre.5/Unity.Collections/NativeList.cs:176)
Unity.Collections.NativeList`1[T]..ctor (System.Int32 initialCapacity, Unity.Collections.AllocatorManager+AllocatorHandle allocator) (at Library/PackageCache/com.unity.collections@1.0.0-pre.5/Unity.Collections/NativeList.cs:120)
Unity.Netcode.NetworkList`1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] values) (at Library/PackageCache/com.unity.netcode.gameobjects@1.0.0-pre.2/Runtime/NetworkVariable/Collections/NetworkList.cs:13)
Bag.PostNetworkVariableWrite () (at Assets/Scripts/Resources/Bag.cs:8)

To Reproduce Steps to reproduce the behavior:

  1. Use public NetworkList<Item> items { get; } = new NetworkList<Item>(new List<Item>()); as class member
  2. Open Unity Editor
  3. See error

Actual outcome No error

Expected outcome N/A

Screenshots image

Environment (please complete the following information):

Additional context N/A

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
mattwalsh-unitycommented, Mar 9, 2022

There is a straightforward workaround, namely, to move the instantiation into your Awake function.

0reactions
aefnorcommented, Apr 15, 2023

@ashwinimurt ashwinimurt why is this a won’t fix? Your docs are literally broken

using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using System;


public struct PlayerData : INetworkSerializable, IEquatable<PlayerData> {
    public FixedString512Bytes playerName;
    public ulong clientId;
    
    public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    {
        serializer.SerializeValue(ref playerName);
        serializer.SerializeValue(ref clientId);
    }
    public bool Equals(PlayerData other)
    {
        return playerName == other.playerName && clientId.Equals(other.clientId);
    }
}
public class TeamManagerNetwork : NetworkBehaviour
{
    public NetworkList<PlayerData> playerData;

    // Use this method to add a new PlayerData to the list
    public void AddPlayerData(PlayerData data)
    {
        playerData.Add(data);
    }

    // Use this method to remove a PlayerData from the list
    public void RemovePlayerData(PlayerData data)
    {
        playerData.Remove(data);
    }
    void Awake () {
        playerData = new NetworkList<PlayerData>();
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Even following the advice to move the instantiation to Awake() I still have issues.

Link from Unity Docs - https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/index.html#synchronizing-complex-types-example

{
    // ^^^^^^^ including all code from previous example ^^^^^^^

    // The weapon booster currently applied to a player
    private NetworkVariable<WeaponBooster> PlayerWeaponBooster = new NetworkVariable<WeaponBooster>();

    /// <summary>
    /// A list of team members active "area weapon boosters" that can be applied if the local player
    /// is within their range.
    /// </summary>
    private NetworkList<AreaWeaponBooster> TeamAreaWeaponBoosters;

    void Awake()
    {
        //NetworkList can't be initialized at declaration time like NetworkVariable. It must be initialized in Awake instead.
        TeamAreaWeaponBoosters = new NetworkList<AreaWeaponBooster>(); 
    }

    void Start()
    {
        /*At this point, the object hasn't been network spawned yet, so you're not allowed to edit network variables! */
        //list.Add(new AreaWeaponBooster());
    }

    void Update()
    {
        //This is just an example that shows how to add an element to the list after its initialization:
        if (!IsServer) { return; } //remember: only the server can edit the list
        if (Input.GetKeyUp(KeyCode.UpArrow)) 
        {
            TeamAreaWeaponBoosters.Add(new AreaWeaponBooster()));
        }
    }

    public override void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();
        if (IsClient)
        {
            TeamAreaWeaponBoosters.OnListChanged += OnClientListChanged;
        }
        if (IsServer)
        {
            TeamAreaWeaponBoosters.OnListChanged += OnServerListChanged;
            TeamAreaWeaponBoosters.Add(new AreaWeaponBooster()); //if you want to initialize the list with some default values, this is a good time to do so.
        }
    }

    void OnServerListChanged(NetworkListEvent<AreaWeaponBooster> changeEvent)
    {
        Debug.Log($"[S] The list changed and now has {TeamAreaWeaponBoosters.Count} elements");
    }

    void OnClientListChanged(NetworkListEvent<AreaWeaponBooster> changeEvent)
    {
        Debug.Log($"[C] The list changed and now has {TeamAreaWeaponBoosters.Count} elements");
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

NetworkList exploding with custom struct that works with ...
UnityException: EditorPrefsGetInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake ...
Read more >
Class NetworkList<T> | Netcode for GameObjects | 1.2.0
Type, Name, Description. FastBufferReader, reader. The stream to read the delta from. Boolean, keepDirtyDelta. Whether or not the delta ...
Read more >
UnityException: get_time is not allowed to be called from ...
I'm trying to make a method that prevents player from spamming Space key. using System.Collections; using System.Collections.Generic; using ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found