我有一个主要代码,用于存储有关玩家的所有信息:
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 指令或程序集引用?)
(现实中存在
healthUp
变量,这才是真正的错误码)
问题可以通过接受数据
CarAttachment1Data
或CarAttachment2Data
来解决,但是我需要变量同时取两个可能的类,因为这个选项是允许的
类不能组合,因为在统一中它们是完全不同的对象,但它们包含在主脚本中获取它们所需的相同类
试过
public interface
但它会产生错误
尝试询问 chatGPT 问题,但无济于事
在 C# 中不能声明 2 种不同类型的变量。您可以将通用功能移动到基类中:
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);
}
}
}