【问题标题】:Detecting two tags in Unity3D for player death在 Unity3D 中检测玩家死亡的两个标签
【发布时间】:2015-07-22 20:36:50
【问题描述】:
我正在制作一个经典的陷阱,两堵墙会合在一起砸碎玩家。为此,我创建了两个单独的标签,“Crush”和“Crush1”,并为每面墙分配了一个标签。这是我的播放器类的代码:
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Crush" && other.transform.tag == "Crush1")
{
Die ();
}
}
我只希望玩家在两面墙同时接触到玩家时被摧毁。当我删除参数中的一个标签时,该方法工作正常(只是不是我想要的)。我确定这里有一个简单的解决方法,我只是没有看到它。感谢您的帮助!
【问题讨论】:
标签:
c#
methods
unity3d
tags
【解决方案1】:
@Christiopher G 说你需要在旗帜击中你(并停止击中你)时存储它们是正确的。
我认为他有点臃肿,但由于不需要新类,您当前的代码很容易扩展以执行您想要的操作。
注意:Unity 目前不可用,因此未经测试。
bool wall1 = false;
bool wall2 = false;
void Update()
{
if( wall1 && wall2 )
{
Die();
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Crush")
{
wall1 = true;
}
else if(other.transform.tag == "Crush1")
{
wall2 = true;
}
}
void OnCollisionExit(Collision other)
{
if (other.transform.tag == "Crush")
{
wall1 = false;
}
else if(other.transform.tag == "Crush1")
{
wall2 = false;
}
}
【解决方案2】:
您可以做的是使用以下代码创建一个脚本并将其附加到您的两个 Wall 对象:
public class WallScript : MonoBehaviour
{
[HideInInspector] //Optional Attribute
public bool collidedWithPlayer;
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == "Player")
{
collidedWithPlayer = true;
}
}
private void OnCollisionExit(Collision collision)
{
if(collision.gameObject.name == "Player")
{
collidedWithPlayer = false;
}
}
//We don't want "collidedwithPlayer" to remain true if either of the walls touches the player before both do so we call "OnCollisionExit" to set it to false.
}
然后在您的播放器脚本中执行以下操作:
private WallScript wall1Script;
private WallScript wall2Script;
private void Awake()
{
wall1Script = GameObject.Find("Wall1").GetComponent<WallScript>();
wall2Script = GameObject.Find("Wall2").GetComponent<WallScript>();
}
或
private WallScript wall1Script;
private WallScript wall2Script
public GameObject wall1;
public GameObject wall2; //Assign GameObjects in Inspector
private void Awake()
{
wall1Script = wall1.GetComponent<WallScript>();
wall2Script = wall2.GetComponent<WallScript>();
}
然后在同一个脚本中:
private void Update()
{
if(wall1Script.collidedWithPlayer && wall2Script.collidedWithPlayer)
{
//Do Something here
}
}
【解决方案3】:
你知道,当玩家接触两堵墙时。
函数OnCollisionEnter 将被执行两次。
第一次,other.transform.tag == "Crush" 是真的。
第二次,other.transform.tag == "Crush1" 是真的。
在OnCollisionEnter、other 中只有一个标签。
如果tag1 != tag2tag == tag1 && tag == tag2 永远不会是真的