首页 > 解决方案 > 如何通过光线投射从列表引用中删除游戏对象

问题描述

嗨,我正在尝试创建一个纸牌游戏,我有一个名为 hand 的类,这只手有一个public List<GameObject> cards;和一个方法:

public void AddCard(GameObject card)
{
   cards.Add(card);
   GameObject cardObject = Instantiate(card, startPosition, actualCardRotation);
}

public GameObject RemoveCard(GameObject card)
{
        cards.Remove(card);
        return card;
 }

然后我有一个 cardGameController 属性public Hand playerHand, computerHand;,该属性具有选择要播放的卡片并调用 RemoveCard 函数的功能,但它在这里不起作用是代码:

public void SelectCardToPlay()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

        RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
        if (hit.collider != null && hit.collider.CompareTag("Card"))
        {
            Console.text = hit.collider.gameObject.GetComponent<Card>().description;

            if (Input.GetMouseButtonDown(0))
            {
                playedPlayerCard = playerHand.RemoveCard(hit.collider.gameObject);
                playerSelectedCardBoard.AddCard(playedPlayerCard, 3);

                playedComputerCard = computerHand.PickRandomCard();
                computerSelectedCardBoard.AddCard(playedComputerCard, 3);

                gameState = 5;
            }
        }
    }

似乎我通过 hit.collider 得到的对象与手牌列表或类似的东西不一样,有什么提示吗?

标签: c#unity3d

解决方案


在您的 AddCard 中,您正在添加输入卡,我假设它是一个预制件 - 因为您使用它来生成一张新卡。然后我假设您要从列表中删除这张生成的卡片,因为这可能是您要击中的对象?

只需将您的 AddCard 更改为:

public void AddCard(GameObject card)
{
   GameObject cardObject = Instantiate(card, startPosition, actualCardRotation);
   cards.Add(cardObject);
}

看看这是否有效。


如果这不是问题,请确保您准确调试您所得到的对象。Debug.Log(gameObject.name);在这里和那里添加一些以查看。


推荐阅读