如何在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
相关产品推荐
相关产品推荐

