首页 > 解决方案 > 禁用特定游戏对象

问题描述

所以,我正在制作一个硬币系统。当玩家与触发对撞机发生碰撞时,我希望它仅禁用与它发生碰撞的对象。

this.SetActive(false); 按名称查找对象

void OnTriggerEnter (Collider other)
{
    if (other.tag == "Coin")
    {
        this.SetActive(false);
    }
}

/

标签: c#unity3d

解决方案


您与原始解决方案非常接近,但您可能误解了这里实际发生的情况。所以我已经记录了我的解决方案以显示差异。

/* The following script is called when a Rigidbody detects a collider that is
 * is set to be a trigger. It then passes that collider as a parameter, to this 
 * function.
 */
void OnTriggerEnter (Collider other) 
{ 
    // So here we have the other / coin collider

    // If the gameObject that the collider belongs to has a tag of coin
    if (other.gameObject.CompareTag("Coin")) 
    {
        // Set the gameObject that the collider belongs to as SetActive(false)
        other.gameObject.SetActive(false); 
    }
}

如果您希望硬币从场景中移除,因为您不希望它被重新激活,那么您可以将此代码修改为以下内容:

void OnTriggerEnter (Collider other) 
{                     
    if (other.gameObject.CompareTag("Coin"))
    {  
        // Removes the coin from your scene instead            
        Destroy(other.gameObject);
    }
}

推荐阅读