Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Last active March 30, 2026 18:17
Show Gist options
  • Select an option

  • Save drewolbrich/1e9d3da074c8a1d5ca93721124b97596 to your computer and use it in GitHub Desktop.

Select an option

Save drewolbrich/1e9d3da074c8a1d5ca93721124b97596 to your computer and use it in GitHub Desktop.
An Entity extension that supports animated changes the opacity of an entity and its descendants
//
// Entity+Opacity.swift
//
// Created by Drew Olbrich on 10/25/23.
// Copyright © 2023 Lunar Skydiving LLC. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import RealityKit
import Combine
public extension Entity {
/// The opacity value applied to the entity and its descendants.
///
/// `OpacityComponent` is assigned to the entity if it doesn't already exist.
var opacity: Float {
get {
return components[OpacityComponent.self]?.opacity ?? 1
}
set {
if newValue >= 1 {
// If we set the opacity to 1, it's best to remove the `OpacityComponent`, or
// otherwise RealityKit appears to treat the entity hierarchy as transparent for
// model sort order purposes, which may introduce unwanted behavior.
components.remove(OpacityComponent.self)
} else {
if !components.has(OpacityComponent.self) {
components[OpacityComponent.self] = OpacityComponent(opacity: newValue)
} else {
components[OpacityComponent.self]?.opacity = newValue
}
}
}
}
/// Sets the opacity value applied to the entity and its descendants with optional animation.
///
/// `OpacityComponent` is assigned to the entity if it doesn't already exist.
///
/// ## Note
/// When this method executes, RealityKit will log this warning:
/// ```
/// Failed to set override status for bind point component member.
/// ```
/// This appears to be a RealityKit framework limitation that occurs during the animation
/// binding process. The warnings do not affect functionality and can be safely ignored.
func setOpacity(_ opacity: Float, animated: Bool, duration: TimeInterval = 0.2, delay: TimeInterval = 0, completion: (() -> Void)? = nil) {
guard animated else {
self.opacity = opacity
return
}
guard scene != nil else {
completion?()
return
}
if !components.has(OpacityComponent.self) {
components[OpacityComponent.self] = OpacityComponent(opacity: 1)
}
let animation = FromToByAnimation(name: "Entity.setOpacity", to: opacity, duration: duration, timing: .linear, isAdditive: false, bindTarget: .opacity, delay: delay)
do {
let animationResource: AnimationResource = try .generate(with: animation)
let animationPlaybackController = playAnimation(animationResource)
if completion != nil {
// `cancellable` is captured by the `receiveCompletion` closure below, forming a
// temporary retain cycle that keeps the subscription alive without any external
// storage. When the publisher completes (after `.first()` receives the animation
// event), `receiveCompletion` sets `cancellable` to nil, breaking the cycle and
// deallocating the subscription.
var cancellable: AnyCancellable?
cancellable = scene?.publisher(for: AnimationEvents.PlaybackCompleted.self, on: self)
.filter { $0.playbackController == animationPlaybackController }
.first()
.sink(
receiveCompletion: { _ in cancellable = nil },
receiveValue: { [weak self] _ in
if opacity >= 1 {
// If we set the opacity to 1, it's best to remove the `OpacityComponent`, or
// otherwise RealityKit appears to treat the entity hierarchy as transparent for
// model sort order purposes, which may introduce unwanted behavior.
self?.components.remove(OpacityComponent.self)
}
completion?()
}
)
// Suppress the "written to, but never read" warning. The compiler doesn't
// recognize the closure capture of `cancellable` as a read, but it IS used:
// `receiveCompletion` sets it to nil to break the retain cycle.
_ = cancellable
}
} catch {
assertionFailure("Could not generate animation: \(error.localizedDescription)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment