Skip to content

Commit f147fa5

Browse files
authored
fix(Entity): Fixes Entity race condition (#268)
* refactor(Entity): encapsulate entity property assignments in a helper function for improved readability and maintainability * fix(Entity): resolve race condition in transform prop assignment for Entity component
1 parent deab2a7 commit f147fa5

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

.changeset/fruity-eagles-peel.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@playcanvas/react": patch
3+
---
4+
5+
Fixes a race condition with the Entity component when setting transform props

packages/lib/src/Entity.tsx

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,20 @@ export const Entity = forwardRef<PcEntity, EntityProps> (function Entity(
6969
// Check if the entity has pointer events attached
7070
const hasPointerEvents = !!(onPointerDown || onPointerUp || onPointerOver || onPointerOut || onClick);
7171

72+
// Helper function to apply entity properties
73+
const applyEntityProperties = (e: PcEntity) => {
74+
e.name = name;
75+
e.setLocalPosition(...position as [number, number, number]);
76+
e.setLocalScale(...scale as [number, number, number]);
77+
e.setLocalEulerAngles(...rotation as [number, number, number]);
78+
};
79+
7280
// Create the entity only when 'app' changes
73-
const entity = useMemo(() => new PcEntity(undefined, app), [app]) as PcEntity
81+
const entity = useMemo<PcEntity>(() => {
82+
const e = new PcEntity(undefined, app);
83+
applyEntityProperties(e);
84+
return e;
85+
}, [app]) as PcEntity;
7486

7587
useImperativeHandle(ref, () => entity);
7688

@@ -111,11 +123,9 @@ export const Entity = forwardRef<PcEntity, EntityProps> (function Entity(
111123

112124
}, [app, parent, entity, onPointerDown, onPointerUp, onPointerOver, onPointerOut, onClick]);
113125

126+
// Update entity properties when they change
114127
useLayoutEffect(() => {
115-
entity.name = name;
116-
entity.setLocalPosition(...position as [number, number, number]);
117-
entity.setLocalScale(...scale as [number, number, number]);
118-
entity.setLocalEulerAngles(...rotation as [number, number, number]);
128+
applyEntityProperties(entity);
119129
}, [entity, name, position, scale, rotation]);
120130

121131
return (<>

0 commit comments

Comments
 (0)