我已经创建了可脚本编写的>>对象自定义类卡片:
这样的对象:[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到可脚本对象类Card: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
强制转换为ScriptableObject类类型?GameObject g = RaycastOpenedCard("CardUIPrefabOpened"); if (g != null) { if (ActiveCards != null && ActiveCards.Count < 5) { Mplayer.ActiveCards.Add(g.GetComponent<Card>()); } }
是否可以将Unity GameObject
错误:
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;公共字符串...
简单地说,不,不可能将GameObject
强制转换为ScriptableObject
,或者与此相反。这是因为GameObject
不继承自ScriptableObject
,ScriptableObject
也不继承自GameObject
。但是,它们都直接继承自Object
。