Changing instance parameters lead to changes in all instances

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

Hi all,

Below is the description of a test.

  1. Create a scene called test with a node of “Area2D” followed by a “CollisionShape2D”.
  2. Set the “Shape” of “CollisionShape2D” as “ConvexPolygonShape2D” with size of “Points” increased to 3.
  3. Create another scene and attach a script as shown below.
  4. Turn on “Visible Collision Shapes” under “Debug” option, and run it.
  5. I expect only t1 is assigned new values and leads to a triangle, while t2 should be nothing on the screen.
  6. But you will see 2 triangles with exact same shape (different position) on the screen.
  7. If you add more instances, you will get more identical triangles. And if you modify anyone of the instances, the other one will be changed.
  8. I’m using Godot v3.2.1

 onready var TEST = preload("res://test.tscn")
    func _ready():
         var t1 = TEST.instance()
         add_child(t1)
         var p0 = Vector2(0,0)
         var p1 = Vector2(100,0)
         var p2 = Vector2(100,100)
         t1.get_node("CollisionShape2D").shape.points = PoolVector2Array([p0,p1,p2])
         
        var t2 = TEST.instance()
        add_child(t2)
        t2.position = t1.position + Vector(500,0)

Please help. Thanks in advance.

:bust_in_silhouette: Reply From: kidscancode

This is expected behavior. Resources are shared (ie passed by reference) among instances. If you want to make a unique shape for each instance, duplicate it first:

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

Or, since you’re going to make unique ones anyway, leave it blank in the original scene and create a new shape:

var poly = ConvexPolygonShape2D.new()
poly.points = PoolVector2Array([p0,p1,p2])
t1.get_node("CollisionShape2D").shape = poly

Thanks for your fast reply!

Your solution works! The problem is solved.

I did not realized “Shape” in the “CollisionShape2D” is treated as “Resources”.
How can I know which part of an object is treated as “Resources”?

andrew.cw | 2020-08-10 06:38

Resources are data container objects. Every object is defined in the documentation:

All classes — Godot Engine (stable) documentation in English

Here you can look up what type of object it is, properties, etc. You can also search this in the editor.

kidscancode | 2020-08-10 06:53

I see. Thanks a lot :slight_smile:

andrew.cw | 2020-08-10 08:59