C#对象销毁其父对象

huangapple go评论67阅读模式
英文:

C# object destroying its parent

问题

我正在使用Unity制作一个2D游戏。我有一个物体,它会摧毁一切接触到的东西。当我启动游戏时,这个物体立即摧毁了它自己的父物体和自身。我希望它在碰撞时摧毁其他物体,但不包括它的父物体。有没有办法实现这个?(是否有类似"isParent"的东西?)

以下是代码部分:

if (other.CompareTag("Room"))
{
    Destroy(other.gameObject);
    Debug.Log("Room Destroyed");
}
英文:

I am making a 2D game in Unity. I have an object, which destroys everything it touches. When I start the game, the object instantly destroys its parent and itself. I would like it to destroy objects on collision, but not if object is its parent. Is there a way to do it? (isnt there something like isParent?)

Code is here:

if (other.CompareTag("Room"))
		{
			Destroy(other.gameObject);
			Debug.Log("Room Destroyed");
		}

答案1

得分: 1

if (other.CompareTag("Room") && transform.parent != other.gameObject.transform)
{
Destroy(other.gameObject);
}

Though, you might want to check if other is anywhere in this object's hierarchy, rather than just checking to see if it's the immediate parent.

英文:
if (other.CompareTag("Room") && transform.parent != other.gameObject.transform)
{
  Destroy(other.gameObject);
}

Though, you might want to check if other is anywhere in this object's hierarchy, rather than just checking to see if it's the immediate parent.

huangapple
  • 本文由 发表于 2023年3月7日 01:14:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定