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

如何在C#的Player类中创建可被主脚本访问的数组?

解决方案

你的问题出在把数组声明成了构造函数的局部变量,而且局部变量不能加public修饰符,导致主脚本根本访问不到这个数组。要实现可外部访问的数组,需要把它定义为类的公共成员,再在构造函数里完成初始化。

修改后的代码如下:

class Player
{
    public int HP;
    public int maxHP;
    public int damage;
    public double critChance;
    public double critMultiplier;
    public int spellCount;
    // 将数组声明为类的公共成员,允许外部访问
    public string[] spells;
    
    public Player()
    {
        // 在构造函数中初始化数组
        spells = new string[spellCount];
    }
}

额外优化建议

  • 遵循C#命名规范,类名使用大驼峰格式(Player而非player),提升代码可读性。
  • 如果spellCount是动态值,建议将其作为构造函数参数传入,避免初始化时因spellCount为默认值0导致数组长度为0:
public Player(int spellCount)
{
    this.spellCount = spellCount;
    spells = new string[spellCount];
}

修改后,在主脚本中实例化Player对象后,就可以直接通过playerInstance.spells访问该数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:54:56