是否可以将Unity GameObject强制转换为ScriptableObject类类型?

问题描述 投票:0回答:1

我已经创建了可脚本编写的>>对象自定义类卡片:

[CreateAssetMenu(fileName = "Card", menuName = "Card")]
public class Card : ScriptableObject
{
    public new string name;
    public string Description;
    public Sprite HeroImage;
    public int Attack;
    public int Health;
    public int XCoord;
    public int YCoord;
}

我已经通过Unity编辑器添加了大量此类对象,并在2d画布上实例化了诸如GameObjects

这样的对象:
for (int i = 0; i < 5; i++)
{
    GameObject go = Instantiate(CardPrefabTemplate, new Vector3(x_delt, 0, 0), Quaternion.identity) as GameObject;
    go.transform.SetParent(MPlayerOpenedCards.transform, false);
    go.gameObject.name = "CardUIPrefabOpened" + i;
    x_delt += (int)(CardPrefabTemplBackgrRect.rect.width * CardPrefabTemplateBackground.localScale.x) + x_card_margin;
}

通过鼠标单击射线投射后,我得到当前点击的卡片GameObject

GameObject RaycastOpenedCard(string prefabName)
{
    //Set up the new Pointer Event
    m_PointerEventData = new PointerEventData(m_EventSystem);
    //Set the Pointer Event Position to that of the mouse position
    m_PointerEventData.position = Input.mousePosition;
    //Create a list of Raycast Results
    List<RaycastResult> results = new List<RaycastResult>();
    //Raycast using the Graphics Raycaster and mouse click position
    m_Raycaster.Raycast(m_PointerEventData, results);

    if (Input.GetMouseButtonDown(0))
    {
        foreach (RaycastResult result in results)
        {
            if (result.gameObject.transform.parent != null && Regex.IsMatch(result.gameObject.transform.parent.name, prefabName))
            {
                Debug.Log("Hit " + result.gameObject.transform.parent.name);
                return result.gameObject.transform.parent.gameObject;
            }
        }
    }
    return null;
}

在程序的其他部分,我有List<Card> ActiveCards列表,我无法cast

射线投射GameObject到可脚本对象类Card
GameObject g = RaycastOpenedCard("CardUIPrefabOpened");
if (g != null)
{
    if (ActiveCards != null && ActiveCards.Count < 5)
    {
        Mplayer.ActiveCards.Add(g.GetComponent<Card>());
    }
}

是否可以将Unity GameObject

强制转换为ScriptableObject类类型?

错误:

ArgumentException:GetComponent要求所请求的组件'Card'从MonoBehaviour或Component派生,或者是一个接口。UnityEngine.GameObject.GetComponent [T]()(在C:/buildslave/unity/build/Runtime/Export/Scripting/GameObject.bindings.cs:28)BoardManager.Update()(位于Assets / Scripts / BoardManager.cs:202)

我已经创建了可脚本编写的对象自定义类Card:[CreateAssetMenu(fileName =“ Card”,menuName =“ Card”)]公共类Card:ScriptableObject {public new string name;公共字符串...

c# unity3d game-engine
1个回答
0
投票

简单地说,不,不可能将GameObject强制转换为ScriptableObject,或者与此相反。这是因为GameObject不继承自ScriptableObjectScriptableObject也不继承自GameObject。但是,它们都直接继承自Object

© www.soinside.com 2019 - 2024. All rights reserved.