From 8b562543df0c3b87a36c5f98daa8d3c3b48af35e Mon Sep 17 00:00:00 2001 From: PouleyKetchoupp Date: Wed, 22 Sep 2021 18:15:03 -0700 Subject: [PATCH] Don't override KinematicCollision reference when still in use in script In case the reference is stored in script, create a new instance to avoid overriding the previous values. Otherwise, re-use the reference as before to avoid extra allocations. --- scene/2d/physics_body_2d.cpp | 6 ++++-- scene/3d/physics_body.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index 1a6a22aab7f..93268918605 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -981,7 +981,8 @@ Ref KinematicBody2D::_move(const Vector2 &p_motion, bool p Collision col; if (move_and_collide(p_motion, p_infinite_inertia, col, p_exclude_raycast_shapes, p_test_only)) { - if (motion_cache.is_null()) { + // Create a new instance when the cached reference is invalid or still in use in script. + if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) { motion_cache.instance(); motion_cache->owner = this; } @@ -1320,7 +1321,8 @@ Ref KinematicBody2D::_get_slide_collision(int p_bounce) { slide_colliders.resize(p_bounce + 1); } - if (slide_colliders[p_bounce].is_null()) { + // Create a new instance when the cached reference is invalid or still in use in script. + if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->reference_get_count() > 1) { slide_colliders.write[p_bounce].instance(); slide_colliders.write[p_bounce]->owner = this; } diff --git a/scene/3d/physics_body.cpp b/scene/3d/physics_body.cpp index 7a3bb653d7b..ad687bde21f 100644 --- a/scene/3d/physics_body.cpp +++ b/scene/3d/physics_body.cpp @@ -960,7 +960,8 @@ void RigidBody::_reload_physics_characteristics() { Ref KinematicBody::_move(const Vector3 &p_motion, bool p_infinite_inertia, bool p_exclude_raycast_shapes, bool p_test_only) { Collision col; if (move_and_collide(p_motion, p_infinite_inertia, col, p_exclude_raycast_shapes, p_test_only)) { - if (motion_cache.is_null()) { + // Create a new instance when the cached reference is invalid or still in use in script. + if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) { motion_cache.instance(); motion_cache->owner = this; } @@ -1330,7 +1331,8 @@ Ref KinematicBody::_get_slide_collision(int p_bounce) { slide_colliders.resize(p_bounce + 1); } - if (slide_colliders[p_bounce].is_null()) { + // Create a new instance when the cached reference is invalid or still in use in script. + if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->reference_get_count() > 1) { slide_colliders.write[p_bounce].instance(); slide_colliders.write[p_bounce]->owner = this; }