Send Message to class instance containing mesh

Hey there,

maybe it’s just too late. But I cannot seem to find a way to send a message to a class instance of a mesh I picked.
F.e. a bullet casts a ray forward where it’ll hit. Now it want’s to tell the targets Target.ts class which contains the picked mesh it will be hit. How would I (or the bullet :wink: ) do that?

Best, Jan

With a fresh brain I still couldn’t find a built-in solution for this. So I subclassed Mesh like this:

import { Mesh } from "@babylonjs/core";
import { SimpleEventDispatcher } from "strongly-typed-events";

export class CustomMesh extends Mesh {
  public onPick = new SimpleEventDispatcher<string>();

  constructor(mesh: Mesh) {
    super(, mesh.getScene(), mesh.parent, mesh);

Like this, on picking the mesh with a ray, I can check if it’s a CustomMesh and send an event to the owning class of the mesh, which subscribed to its onPick EventDispatcher.

Still, if there’s a built-in - probably more solid way - I’d be interested :smiley:

In general I would have done this with a custom behavior for Mesh : Mesh Behaviors | Babylon.js Documentation

Basically attaching to the default onPick observable and redirect/broadcast when needed.

1 Like

Hmm, don’t waste your time on it as my solution works ok for me. But if you want, correct me if I’m wrong.

Wouldn’t the behavior be executed on the target. So the onPick would also happen on the target mesh?!
How would the bullet be able to send some info to the target without bouncing events back and forth?

Glad your solution works :slight_smile: with behavior as it is custom code you could have put the logic in but no need to change if your solution works.

1 Like

And it broke, once I wanted to convert it to Instanced Meshes :sweat_smile: Making a custom behavior wasn’t that hard after all too =)

Thanks for your help!

For reference, this is what I attach to my mesh. Then I can use the event be getting the behavior once the hit happens.

import { Behavior, Mesh } from "@babylonjs/core";
import { EventDispatcher } from "strongly-typed-events";
import { Interactable_Base } from "../interaction/interactable_base";

export class OnPickBehavior implements Behavior<Mesh> {
  name: string = "onPickBehavior";

  public onPick = new EventDispatcher<Interactable_Base, string>();

  public init(): void {}
  public attach(target: Mesh): void {}
  public detach(): void {}
1 Like