useVariants hook to use KHR Material Variants #2115
+171
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Live Sandbox
Why
The KHR Material Variants GLTF Extension allows you to set multiple materials on multiple meshes within a single GLTF instance. This allows you to create many different versions of objects inside a single gltf file and set a global state object to switch between them.
This is supported within threeJS core: Here
What
This hook takes the returned GLTF object from the standard loader or loaders like
useGLTF
activeVariant
is the string name of the current variantsetVariant
takes the string name input of the variant objectvariants
is an array of of variants that look like{ name: 'variantName' }
( NOTE: I was originally going to simplify this to just be the variant names, but talking with Don it would be possible to add data to variant objects that could be useful. Leaving it this way makes that data accessible)materials
This is less commonly used but is the actual materials array from the GLTF. apps like GLTFJSX actually struggle with gltf material lists and can accidentally merge them or mess them up. Because we are already deep into the GLTF I added this to help me pull them out and read them if needed. It will probably be ignored by most.You can set the variant using the
setVariant
method or as an input to the hook itself.This makes things convienent when the switching logic happens outside the component.
Using
setVariant()
Using direct hook input:
Checklist