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

如何向子类返回数组?解决类型转换报错问题

存档系统类型转换错误解决方案

问题描述

我正在为游戏实现存档系统,计划在基类中填充数组后返回给子类的数组,但始终报错:Cannot implicitly convert type 'PlayerBodyPart[]' to 'PlayerBodyPart'。怀疑是否因为子类的数组元素是struct类型?

基类代码

public class LoadData : MonoBehaviour
{
    public PlayerBodyPart LoadBPdata(string filePath, PlayerBodyPart[] bodyPart)
    {
        int id; int type; string name; int skill; string spritePath; int price; bool isUnlocked;

        int k = -1;

        var lines = File.ReadAllLines(filePath);

        for (int i = 0; i < lines.Length; i++)
        {           
            if (lines[i].Contains("id"))
            {
                k += 1;
                id = Int32.Parse(Regex.Match(lines[i], @"\d+").Value);

                string typ = Regex.Replace(lines[i + 1], "type ", "");
              
                switch(typ)
                {
                    case ("Head"):
                        type = 0;
                        break;
                    case ("Body"):
                        type = 1;
                        break;
                    case ("Arms"):
                        type = 2;
                        break;
                    case ("Legs"):
                        type = 3;
                        break;
                    default:
                        type = 0;
                        break;
                }

                name = lines[i + 2];
                skill = Int32.Parse(Regex.Match(lines[i + 3], @"\d+").Value);
                spritePath = Application.dataPath + lines[i + 4];
                price = Int32.Parse(Regex.Match(lines[i + 5], @"\d+").Value);

                string unlockBool = Regex.Replace(lines[i + 6], "unlocked ", "");

                if (unlockBool == "True") isUnlocked = true;
                else isUnlocked = false;

                Debug.Log($"{id}, {type}, {name}, {skill}, {spritePath}, {price}, {isUnlocked}");
                
                bodyPart[k] = new PlayerBodyPart(id, type, name, skill, spritePath, price, isUnlocked);
            }          
        }
        return bodyPart;
    }
}

子类代码

public struct PlayerBodyPart
{
    public enum PartType { Head, Body, Arms, Legs };

    public int id;
    public PartType type;
    public string name;
    public int skill;
    public Sprite sprite;
    public int price;
    public bool isUnlocked;

    public PlayerBodyPart(int id, int type, string name, int skill, string spritePath, int price, bool isUnlocked)
    {
        this.id = id;
        this.type = (PartType)type;
        this.name = name;
        this.skill = skill;
        this.sprite = Resources.Load("spritePath") as Sprite;
        this.price = price;
        this.isUnlocked = isUnlocked;
    }
}

public class PlayerBPCatalogue : LoadData
{
    public PlayerBodyPart[] PBpart;

    public int n = 1000;

    public void Start()
    {
        PBpart = new PlayerBodyPart[n];
        string filePath = Application.dataPath + "/Data/bodyParts.txt";

        base.LoadBPdata(filePath, PBpart);           
    }   
}

错误原因与修复方案

错误原因

报错和struct无关,核心是方法返回值类型不匹配:
LoadBPdata方法声明返回单个PlayerBodyPart对象,但你实际返回的是PlayerBodyPart[]数组,类型不兼容导致转换错误。

修复步骤

有两种简洁的修复方式:

  1. 修正方法返回值为数组类型
    修改基类方法的签名,把返回值从PlayerBodyPart改为PlayerBodyPart[]:

    public PlayerBodyPart[] LoadBPdata(string filePath, PlayerBodyPart[] bodyPart)
    

    这样返回bodyPart就符合类型要求了,子类调用时可以选择接收返回值(不过数组是引用类型,传入的数组已经被修改,其实可以不用接收)。

  2. 改为无返回值方法
    如果不需要返回数组,直接把方法改为void类型,去掉返回语句:

    public void LoadBPdata(string filePath, PlayerBodyPart[] bodyPart)
    

    然后删除return bodyPart;这一行,子类的调用逻辑保持不变即可。

额外优化建议

  • PlayerBodyPart构造函数中,Resources.Load("spritePath")是硬编码字符串,应该传入实际的参数,改为:
    this.sprite = Resources.Load(spritePath) as Sprite;
    
  • 注意数组越界问题:如果文件中的数据条数超过bodyPart的长度(比如n=1000但数据有1001条),会触发报错,建议添加if(k < bodyPart.Length)的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:55:26