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

Unity C#类成员变量无法访问问题求助

问题解决方法

你的代码有两个核心问题导致无法访问TableHeight:

1. 类成员的访问权限问题

C#里类的字段(成员变量)默认是private(私有),外部类无法直接访问。同时你的Table类定义存在语法错误,类声明不能加括号。

修正后的Table类:

class Table
{
    // 把字段改成public,允许外部访问
    public int TableHeight;            
    public string TableName;

    public Table(int _TableHeight, string _TableName)
    {
        TableHeight = _TableHeight;
        TableName = _TableName;
    }
}

如果想遵循更规范的封装写法,也可以用属性来隐藏内部字段:

class Table
{
    private int _tableHeight;            
    private string _tableName;

    // 只读属性,外部只能获取值不能修改
    public int TableHeight => _tableHeight;
    public string TableName => _tableName;

    public Table(int tableHeight, string tableName)
    {
        _tableHeight = tableHeight;
        _tableName = tableName;
    }
}

2. 变量tab的作用域问题

你在Start方法里定义的tab是局部变量,仅在该方法的代码块内有效。要在方法内后续代码或其他方法中访问它,需要把它提升为TableCreator类的成员变量:

修正后的TableCreator类:

public class TableCreator : MonoBehaviour     
{
    // 将tab定义为类的成员变量
    private Table tab;

    void Start()
    {
        tab = new Table(5, "CrispyWoody");
        // 现在可以正常访问TableHeight了
        int HeightOfTable = tab.TableHeight;
        Debug.Log(HeightOfTable);
    }
}

调整后就能正常访问TableHeight了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:57:03