Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add childadded event dispatch #3214

Merged

Conversation

rubeniskov
Copy link
Contributor

@rubeniskov rubeniskov commented Mar 21, 2024

Three r0.162.0 has now support for childadded event in Object3D's

https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js#L345-L349

Example of implementation for get added objects

import { useEffect, useMemo, useState } from 'react';
import { Layers, Object3D, Object3DEventMap } from 'three';

import { useThree } from '@react-three/fiber';
import useEventCallback from 'use-event-callback';

/**
 * Get all objects in the scene,
 *
 * Inspired in https://github.com/mrdoob/three.js/pull/16934#issuecomment-506793917
 */
export const useSceneObjects = () => {
  const [sceneObjects, setSceneObjects] = useState<Object3D[]>([]);
  const scene = useThree(({ scene }) => scene);

  const addNode = useEventCallback((evt: Object3DEventMap['childadded']) => {
    evt.child.traverse((node) => {
      node.addEventListener('childadded', addNode);
      node.addEventListener('childremoved', removeNode);
        setSceneObjects((prev) => [...prev, node]);
    });
  });

  const removeNode = useEventCallback((evt: Object3DEventMap['childremoved']) => {
    evt.child.traverse((node) => {
      node.removeEventListener('childadded', addNode);
      node.removeEventListener('childremoved', removeNode);
      setSceneObjects((prev) => prev.filter((n) => n !== node));
    });
  });

  useEffect(() => {
    addNode({ child: scene });
  }, [addNode, scene]);

  return sceneObjects;
};

export default useSceneObjects;

Copy link

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit a08dfb6:

Sandbox Source
example Configuration

@CodyJasonBennett CodyJasonBennett changed the title Add childadded event dispatch feat: add childadded event dispatch Mar 24, 2024
@CodyJasonBennett CodyJasonBennett merged commit df4787f into pmndrs:master Mar 25, 2024
2 checks passed
CodyJasonBennett added a commit that referenced this pull request Mar 27, 2024
a4a31ed
#3214
Misc transient Zustand changes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants