Common scene inheritance

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

I have a few items that I would like to be able to drop into the world with different properties but they’re all items that the player can pick up.

  1. Apple
  2. Orange
  3. Ore
  4. Log

They have some properties e.g. consumable.

I have a json for all my objects

  'Apple': {
        'consumable': true,
        'asset_path': 'res://assets/items/apple.png'  
  },
  'Log':  {
        'consumable': false,
        'asset_path': 'res://assets/items/log.png'
  }
}

What’s the best way to structure this?

  1. A scene for each item specifically?
  2. One scene and instantiate the values programmatically?

If it’s option 2, how do I go about it?

var item = Item.instance()
item.set_type('Log')

parent.add_child(item)

How about more complex scenes with timers and triggers? How do you make it more generic and “inheritable”? Thanks!

:bust_in_silhouette: Reply From: magicalogic

If your pickups have many properties in common its best you create a base script then extend the other scripts from it.

Thank you so much. I added the same question below btw.

Would I still create a scene for each one of my items?

Say I have a Timer and a Sprite and Collision box. Do I have to create the same for each item? I think that’s the part I’m confused about.

sas1ni69 | 2021-05-08 04:18

:bust_in_silhouette: Reply From: Ertain

_magicalogic_ had got the right idea on how to set up the scene. Create a base class, Item, and extend it with the other items:

# Base class
class_name Item
var consumable: bool = false
var asset_path: string = ""

# Apple item
extends Item
func _ready():
     consumable = true
     asset_path = "res://assets/items/apple.png"

Thank you so much. Would I still create a scene for each one of my items?

Say I have a Timer and a Sprite and Collision box. Do I have to create the same for each item? I think that’s the part I’m confused about.

sas1ni69 | 2021-05-08 04:18

Only if you wanted to include them among the other items. Have a scene that’s bare bones (e.g. only one Timer, one Sprite, or one collision node), and then instance them as necessary.

Ertain | 2021-05-08 05:58