Is there anything wrong with modyfing a CollisionShape2D value for an instance?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By nwgdusr999

Just wasted hours debugging… It seems that modifying a value of a collider modifies the colliders of all other objects of the current Scene?! This seems like a bug… Code example:

func addTileBlob(var color, i, j, scaleFactor, var targetTilesDict):
    return preload("res://Orb.tscn").instance() ;

func addTileBlobDebug(var color, i, j, scaleFactor, var targetTilesDict):
    var orb = preload("res://Orb.tscn").instance() ;
    orb.get_node("CollisionShape2D").disabled = true;
    orb.get_node("CollisionShape2D").shape.radius = .1;

The last line that modifies the radius seems to cause an issue where ALL of the orbs of the current scene (even those who are not created in this method) at one point have their radius values replaced with .1…!

I guess I have more reading about instancing… Seems quite strange that modifying an instance would modify ALL the other instances eventually without any reason that I can find… Or is this specific to the collider? It doesn’t happen right away, works for a while, then after a few collisions, boom, the radius every orb instance become .1 for no apparent reason… The disabled doesn’t seem to ‘spread’ though… (or something else is wrong I’m my code that I’m totally missing…)

:bust_in_silhouette: Reply From: kidscancode

When changing the shape property of the node, you’re not modifying an instance, you’re modifying a Resource. Resources are shared between instances by default. This is a good thing if you don’t need them to all be different as it saves memory. If you need them to be different, you have to make the shape resource unique. Add this before you set the radius:

orb.get_node("CollisionShape2D).shape = orb.get_node("CollisionShape2D).shape.duplicate()

Ha! So yeah, CollisionShape2D inherits Node2D, while the Shape2D does inherit from Resource, that would explain it thanks!

Would there be a way to somehow duplicate an instance? Like my 2 functions could each potentially generate hundreds of instances… So something like instancing the Orb scene, duplicating the shape, changing the radius, then … re-instancing from the Orb with the duplicated shape instance so all following nodes re-use the shape with the new radius? Or would I have to create a different scene for the .1 radius instances?

nwgdusr999 | 2019-05-31 10:27

Node.duplicate() has you covered there.

kidscancode | 2019-05-31 14:53