[英]Is it possible to cast Unity GameObject to ScriptableObject class type?
我创建了可编写脚本的对象自定义类 Card:
[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 Editor 添加了大量这样的对象,并在 2d Canvas 上实例化了诸如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;
}
通过鼠标单击 Raycast 后,我得到当前单击的 Card 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
名单,我不能够施展Raycasted游戏物体来个ScriptableObject类卡:
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)
简而言之,不,不可能将GameObject
为ScriptableObject
,反之亦然。 这是因为GameObject
不继承ScriptableObject
而且也没有ScriptableObject
从GameObject
。 然而,它们都直接从Object
继承。
之所以行GameObject go = Instantiate(CardPrefabTemplate, new Vector3(x_delt, 0, 0), Quaternion.identity) as GameObject;
是因为Instantiate
将一个Object
作为参数并克隆它,返回一个Object
。 ScriptableObject
是一个Object
因此可以工作。 你可以将一个Object
为一个GameObject
Object
,这样也可以。 但这并没有达到什么效果,因为这样做是Object
部分,所以在您的示例中, Object.name
。
现在GetComponent
失败的原因是因为它只能查找MonoBehaviour
,而ScriptableObject
(Card) 不是。 顺便说一下, MonoBehaviour
也从Object
继承了一个点。
所以真正的问题是你一开始想达到什么目的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.