Sharing Resources Between Instanced Scenes

Apr 03, 2019
Sharing Resources Between Instanced Scenes

A common thing to do in game development is to create hitboxes or hurtboxes that will handle collisions. Usually you want to derive your hitboxes from the same base scene or class so that collisions are always handled in the same manner. However, you may want to change the size of your hitboxes to reflect differently sized weapons, enemies, etc. With Godot, there is a sneaky pitfall that reveals itself when trying to implement dynamically sized hitboxes. This pitfall can be confusing at first - especially for new Godot users. I’ll step through the problem to show you what I’m talking about.

The Setup

I have set up a standalone scene with a root node of type Area2D and a single child of type CollisionShape2D. I have set the collision shape to use a CircleShape2D resource with a radius of 10. 7

Here I’ve created a main scene with 3 instances of the scene I showed you previously. 1

Everything looks good so far so let’s run it to be sure. 2


The Problem

Let’s say that I want to dynamically change the size of the Area2D’s circle: 3 This is not a super intelligent way of setting up dynamically sized hitboxes, but it’s totally fine for demonstration purposes.

So when we run this, we should expect to see 3 differently sized circles right? 4 This is where things take an unexpected turn. The circles have changed sizes, but they are all the same size. What’s the issue?

The issue is that Godot shares resources between instances of a scene by default. Our circle is a CircleShape2D resource, and is shared between the 3 example instances. We are indeed changing the radius 3 times but we change it for the shared resource. The last radius that is set ends up being the radius shared for all instanced scenes.

Fortunately the solution is pretty simple: 5

Checking the Local to Scene box under the Resource tab of the shape resource tells Godot that this resource is independent of the other instanced scenes. Now when we run it we see the result we expected: 6

This behavior is not unique to shape resources. In fact, anything that is classified as a Resource will behave this way. Sometimes it’s perfectly fine, but sometimes it is undesirable.

Hopefully that helps you out. Thanks for reading!

Enjoying this content?

Consider purchasing Sword Slinger on Steam!