[英]Unity - How to detect collision on a child object from the parent GameObject?
I am making a 2D Game with Unity 5 and I have a problem with child GameObject collider. 我正在使用Unity 5进行2D游戏,我遇到了儿童GameObject对撞机的问题。 I want to detect a collision between a Child GameObject with another object, doing this from the parent script and using tags.
我想检测Child GameObject与另一个对象之间的冲突,从父脚本执行此操作并使用标记。
Follow my parent script below: 按照下面的父脚本:
void OnCollisionEnter2D(Collision2D hit) {
if(hit.transform.tag == "Enemy"){
this.playerRigidbody.AddForce(new Vector2(0, this.forceJump));
}
}
The "Enemy" tag is another object that is colliding with the collider of my player child. “Enemy”标签是另一个与我的玩家孩子的碰撞器碰撞的物体。 I want to detect the collision between the child object and that another object, I searched in many similar forums about Unity but I couldn't solve my problem.
我想检测子对象和另一个对象之间的冲突,我在很多类似的论坛中搜索过关于Unity但我无法解决我的问题。 Someone can help me with this problem?
有人可以帮我解决这个问题吗?
When a collision occurs, Unity will search up the hierarchy for the nearest Rigidbody and run any scripts on that same GameObject. 发生冲突时,Unity将在层次结构中搜索最近的Rigidbody并在同一GameObject上运行任何脚本。
So, the simple approach is to make sure the rigidbody is on the parent object with the script. 因此,简单的方法是使用脚本确保刚体在父对象上。 Here's an example hierarchy:
这是一个示例层次结构:
Parent has: 家长有:
Child B has: B儿童有:
When the box collider collides with something, the event will bubble up straight through Child A and be received by the Rigidbody on the parent, which will then cause the script to run. 当盒式对撞机与某些东西发生碰撞时,该事件将直接通过Child A冒泡并被父级的Rigidbody接收,这将导致脚本运行。
Unity won't bubble the event up the hierarchy any further than that for performance reasons. 出于性能原因,Unity不会将事件在层次结构中冒泡。 So, your other options are..
所以,你的其他选择是......
Add a script to the child which catches the collision and deals with it there. 向捕获碰撞的子项添加一个脚本并在那里处理它。 If you need to, you could forward the event to the parent script like so:
如果需要,您可以将事件转发到父脚本,如下所示:
void OnCollisionEnter2D(Collision2D hit) { // Forward to the parent (or just deal with it here). // Let's say it has a script called "PlayerCollisionHelper" on it: PlayerCollisionHelper parentScript = transform.parent.GetComponent<PlayerCollisionHelper>(); // Let it know a collision happened: parentScript.CollisionFromChild(hit); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.