我创建了可编写脚本的对象自定义类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后,我得到当前单击的卡 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
列表,我无法投射光线投射 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)
答案 0 :(得分:1)
简单地说,不,不可能将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.name
。
现在GetComponent
失败的原因是因为它只能寻找MonoBehaviour
(ScriptableObject
(卡)不是)。 MonoBehaviour
还会从Object
继承一点。
所以真正的问题是,您首先想实现什么目标?