unity3d 如何正确创建接受不同类的变量

myzjeezk  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(82)

我有一个主代码,存储有关球员的所有信息:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "CarData", menuName = "Data/Car/CarData")]
public class CarData : ScriptableObject
{
    [SerializeField] public ScriptableObject carAttachmentData;
    private int playerHealth;
    void Start()
    {
        playerHealth = carBodyData.health;
    }
}

我需要这个变量只接受两个类,即:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "CarAttachment1Data", menuName = "Data/Car/CarAttachmentData")]
public class CarAttachment1Data : ScriptableObject
{
    public int health; //for example
}

以及

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "CarAttachment2Data", menuName = "Data/Car/CarBodyData")]
public class CarAttachment2Data : ScriptableObject
{
    public int health; //for example
}

编译时单元报错:
“ScriptableObject”不包含“healthUp”的定义,并且找不到接受“ScriptableObject”类型的第一个参数的可访问扩展方法“healthUp”(是否缺少using指令或程序集引用?)
(in实际上,healthUp变量存在,这是真正的错误代码)
这个问题可以通过接受数据CarAttachment1DataCarAttachment2Data来解决,但是我需要变量同时接受两个可能的类,因为这个选项是允许的
类不能组合,因为在一个整体中它们是完全不同的对象,但它们包含在主脚本中获取它们所需的相同类
已尝试public interface,但生成错误
我尝试询问chatGPT问题,但没有帮助

n9vozmp4

n9vozmp41#

在C#中不可能声明两种不同类型的变量。可以将公共功能移到基类中:

using UnityEngine;

public class CarBase : ScriptableObject
{
    public int Health;
}

子类:

using UnityEngine;  

[CreateAssetMenu(fileName = "Truck", menuName = "Truck", order = 0)]
public class Truck : CarBase
{
    public int LoadCapacity;
}

以及

using UnityEngine;

[CreateAssetMenu(fileName = "Taxi", menuName = "Taxi", order = 0)]
public class Taxi : CarBase
{
    public int PassengersCount;
}

在编辑器中,您可以保存2个不同的资产“出租车”和“卡车”,并检查类型的调用代码:

using UnityEngine;

public class Garage : MonoBehaviour
{
    [SerializeField] private CarBase carInfo;

    public void Awake()
    {
        Debug.Log(carInfo.Health);
        if (carInfo is Taxi)
        {
            var taxiInfo = (Taxi)carInfo;
            Debug.Log(taxiInfo.PassengersCount);
        }
    }
}

相关问题