Setting variable inherited from parent resource in child resource script

Say if I have this parent resource script


Extends Resource

Class_name Item

@export var sellable: bool

And a child resource script:


Extends Item

Class_Name FoodItem

Is there a way for me to set sellable to true in the FoodItem script, so all resources that are created with the FoodItem script have sellable = true in the inspector by default?

I can’t set sellable to true in the Item script because not all resources that inherit from Item are sellable (eq. A QuestItem won’t be sellable), but I don’t want to have to manually tick the bool to true in the inspector every time I create a new FoodItem resource.
Same with exported enums and ints. Thanks!

You should be able to do this with the _init method, see here

1 Like

I had a read through of the documentation, but unfortunately I’m afraid I still don’t quite understand…

I tried doing this:

Extends Item

Class_Name FoodItem 

func _init(food_sellable = true):
    sellable = food_sellable

But whenever I make a new FoodItem, the sellable bool in the inspector still appears to be false.

Then I’d suggest making the init function for Item the same and calling it from FoodItem with the argument, like so:

extends Resource

class_name Item

@export var sellable: bool

func _init(food_sellable = false):
    sellable = food_sellable
extends Item

class_name FoodItem 

func _init(food_sellable = true):
    super(food_sellable)

That seemed to work! Thanks!!!

1 Like

Sorry, one more question…

What if I’m not trying to set a bool via _init(), but the first item in an array of enums instead? For example in the item script:


Extends Resource

Class_Name Item 

@export var item_type: Array[type]

Enum type{WEAPON, FOOD, OTHER}

I want the first thing in the item_type array in any FoodItems created to always be FOOD. I tried passing in an array as an argument in the script like this:


Func _init(food_type[0] = type.FOOD):
item_type[0] = food_type[0] 

However, again, it’s not really working…and I’m getting a expected closing “)” after function parameters

The argument should be without the [0], but if the array is empty you need to add it with push_back instead, or item_type = [food_item]

Ermmm…sorry, I don’t think I get it. Can you give an example? Thanks :face_with_spiral_eyes:

func _init(food_type = type.FOOD):
    item_type = [food_type]

Or

func _init(food_type = type.FOOD):
    item_type.push_back(food_type)

It worked!! I can’t thank you enough, I’ve been puzzling over this for days haha. Thank you so much!!!

1 Like

No problem! Happy it works!