当粒子击中碰撞体时,将调用 OnParticleCollision。

可用于在被粒子击中时对 GameObject 施加伤害。

Legacy Particle System:
This message is sent to all scripts attached to the WorldParticleCollider and to the Collider that was hit. The message is only sent if you enable sendCollisionMessage in the Inspector of the WorldParticleCollider.

// Legacy Particle System example
// Applies a force to all Rigidbody components that are hit by the particle.

using UnityEngine; using System.Collections;

public class ExampleClass : MonoBehaviour { void OnParticleCollision(GameObject other) { Rigidbody body = other.GetComponent<Rigidbody>();

if (body) { Vector3 direction = other.transform.position - transform.position; direction = direction.normalized; body.AddForce(direction * 5); } } }

Shuriken Particle System:
This message is sent to scripts attached to Particle Systems and to the Collider that was hit.

当从附加到 GameObject(该 GameObject 具有 Collider)的脚本调用 OnParticleCollision 时, GameObject 参数表示 ParticleSystem。在任何给定帧内, 对于与其发生碰撞的每个粒子系统,Collider 最多只收到一条消息, 即使粒子系统在当前帧中使用多个粒子击中该 Collider 也是如此。 要检索 ParticleSystem 造成的所有碰撞的详细信息, 必须使用 ParticlePhysicsExtensions.GetCollisionEvents 检索 ParticleSystem.CollisionEvent 的数组。

当从附加到 ParticleSystem 的脚本调用 OnParticleCollision 时, GameObject 参数表示附加了被 ParticleSystem 击中的 ColliderGameObject。 对于每个被击中的 ColliderParticleSystem 最多收到一条消息。 如上所述,必须使用 ParticlePhysicsExtensions.GetCollisionEvents 来检索 GameObject 上的所有碰撞事件。

仅当在 Particle System Collision 模块的 Inspector 中启用了 Send Collision Messages 时,才发送消息。

OnParticleCollision 可以作为协同程序使用 - 在函数中使用 yield 语句即可。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ExampleClass : MonoBehaviour { public ParticleSystem part; public List<ParticleCollisionEvent> collisionEvents;

void Start() { part = GetComponent<ParticleSystem>(); collisionEvents = new List<ParticleCollisionEvent>(); }

void OnParticleCollision(GameObject other) { int numCollisionEvents = part.GetCollisionEvents(other, collisionEvents);

Rigidbody rb = other.GetComponent<Rigidbody>(); int i = 0;

while (i < numCollisionEvents) { if (rb) { Vector3 pos = collisionEvents[i].intersection; Vector3 force = collisionEvents[i].velocity * 10; rb.AddForce(force); } i++; } } }