You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity CS0273错误修复咨询:Singleton属性set访问器权限问题

修复Unity NetworkManager脚本中的CS0273错误

错误原因

CS0273错误的核心逻辑是:属性的访问器修饰符必须比属性本身的访问级别更严格。你的代码里Singleton属性是private的,同时给set访问器也加了private修饰符,两者权限级别完全一致,违反了C#的语法规则。

修复步骤

  1. 移除set访问器的private修饰符
    因为Singleton属性本身已经是private,其访问器默认就是私有级别,不需要额外标注private。

  2. 修复参数传递错误
    代码里Server.Start(port.maxClientCount)的写法有误,Riptide的Server.Start需要两个独立参数,应该用逗号分隔而非点运算符。

修正后的完整代码

using RiptideNetworking;
using RiptideNetworking.Utils;
using UnityEngine;

public class NetworkManager : MonoBehaviour
{
    private static NetworkManager _singleton;

    private static NetworkManager Singleton
    {
        get => _singleton;
        set
        {
            if (_singleton == null)
                _singleton = value;
            else if (_singleton != value)
            {
                Debug.Log($"{nameof(NetworkManager)} instance already exists, destroying duplicate!");
                Destroy(value);
            }
        }
    }

    public Server Server { get; private set; }

    [SerializeField] private ushort port;
    [SerializeField] private ushort maxClientCount;

    private void Awake()
    {
        Singleton = this;
    }

    private void Start()
    {
        RiptideLogger.Initialize(Debug.Log, Debug.Log, Debug.LogWarning, Debug.LogError, false);

        Server = new Server();
        Server.Start(port, maxClientCount);
    }

    private void FixedUpdate()
    {
        Server.Tick();
    }

    private void OnApplicationQuit()
    {
        Server.Stop();
    }
}

额外优化建议(可选)

如果需要让外部代码能访问单例实例(这是单例模式的常见需求),可以把Singleton属性改为public,同时保留set访问器的private修饰符,这样外部只能读取实例、不能修改,更符合单例的设计规范:

public static NetworkManager Singleton
{
    get => _singleton;
    private set
    {
        // 原有逻辑不变
    }
}

内容的提问来源于stack exchange,提问作者Iceigloopenguin Plays

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:45:35