Accessing a custom object in an array

Godot Version

4.6

Question

Hi, so for my coffee shop game I wanted to create two different classes. A products class that I can use to create resources that hold drinks like espresso and drip coffee and what not, and an ingredients class that just holds the cost per part for each ingredient used. The ingredients used for each product is stored in an array that I set up when I make the drink and then the cost and selling price would be set in the _init() function. However, I cannot get the cost per part from the array in the products class script every time I try I get the Invalid access to object or property error. Honestly I’m just stumped I really don’t know what I’m doing a good portion of the time and I’m starting to get worried that I’ve wasted a night of work on this. I’ve included the relevant scripts.

Product Class Script:

extends Resource

class_name Product

@export var temp : String
@export var ingredients : Array
@export var expenses : float 
@export var selling_price : float = expenses + (expenses * 0.5)

func _init() -> void:
	var cycle_counter : int = 0
	for i in ingredients:
		if ingredients.size() > 0:
			#This is the line that breaks the script
			expenses += ingredients.get(cycle_counter).cost_per_part
			ingredients.push_back(Ingredients)
			cycle_counter += 1
		else:
			pass

Ingredients Class Script:

extends Resource

class_name Ingredients

@export var cost_per_part : float

Test Script:

Currently prints nothing as I can’t get espresso to work

extends Node

@onready var espresso : Resource = preload("res://products/espresso.tres")._init()


func _ready() -> void:
	print(espresso.temp)
	print(espresso.ingredients)
	print(espresso.expenses)
	print(espresso.selling_price)

I don’t know how to use the resource node but try :

  1. Using a singleton or making the resource a singleton which is generally accessible, but I don’t think it’s safe for performance reason

  2. Try using a normal extended node script and rearrange it

This should be giving you an error.
_init() is a function of the Product class (technically it is the constructor). It does not return a value.
What your code is doing is trying to assign the return value of _init() to the variable espresso.
_init() is a constructor so it will run automatically when you create a new Product instance.
preload used with a .tres file will return an instance of the class (in this case Product class).
If you are going to use it then use the type (@onready not necessary here):
var espresso:Product = preload("res://products/espresso.tres")
Since this statement returns an instance of the resource (in this case an instance of the Product class) it will run the _init() automatically.
Always type your variables and at the very least you will get much better error messages.

So removing the ._init() removed the error. It’s still not properly accessing the cost per part variable in the actual _init() function. Just now no errors. I did double check my variables I have been typing them correctly, at least as far as I can tell, the espresso variable in the test script is the only one I think I did incorrect. Thank you for pointing out that I can type it with the custom class I don’t know how I forgot that.

As is it runs the _init() function just fine and if I use something simple like expenses = 5 it does set that, but it will not add the cost that I have set in the ingredients resource.

After messing around with it for a little bit this is what I’m at. As is it seems to act like the variables haven’t been changed for the new resource, so for example the reason I put the placeholders in was because it was reading the array size as 0 even though the espresso product resource had an array size of 2.

extends Resource

class_name Product

@export var temp : String
@export var ingredients : Array = ["placeholder", "placeholder", "placeholder", "placeholder"]
@export var expenses : float 
@export var selling_price : float = expenses + (expenses * 0.5)

func _init() -> void:
	var cycle_counter : int = 0
	for i in ingredients.size():
		if ingredients.get(cycle_counter) == "placeholder":
			pass
		else:
			expenses += ingredients.get(cycle_counter).cost_per_part
			print(str(ingredients.get(cycle_counter).cost_per_part))
		cycle_counter += 1

Apologizes if I haven’t explained something well, this is the first full project I’ve started on without the help of a template tutorial. I’ve been working off very a rudimentary understanding of code in general so it’s not been fun but I feel like I’m learning a lot.

One way to make it easier would perhaps be to just use a resource. Right now you are using a node that just seems to be an extension of a resource. Or will you add some functionality later, in addition to what you have now? If not I would skip extending Node.

Also, I think your cycle counter and those things are very off. You start by setting a cycle counter to 0 that increments by one, and then start looping over an array to access each thing in order. They both are meant to do the same thing. Your “i” and “ingredients.get(cycle_counter)” are essentially the exact same thing and it would be better if you deleted cycle counter and renamed “i” “ingredient” or something like that. “i” is mostly used for ints. Then your line “expenses += ingredients.get(cycle_counter).cost_per_part” would look like “expenses += ingredient.cost_per_part”

Also, in the if ingredients.size() > 0 you push_back() the array. Rearranging or deleting indexes from arrays while iterating over them could cause unexpected behaviors. I would not do any push_back() while iterating over the array. Also, I would completely remove the “if not greater than 0:” check. If it is 0, the loop will not happen either way. Right now, you do it for every ingredient inside ingredients and i believe it has 0 effect on anything but makes the code harder to understand.

The entire init function could i.m.o look like:

for ingredient in ingredients:
	expenses += ingredient.cost_per_part

I have the loop because there’s multiple ingredients needed for each product, as is one line of code would only return the cost of one ingredient when for example the espresso product should have two ingredients at 0.75 cents each. These are all resources, so I have a product class script that is then used to make product resources like espresso.tres the one I’m trying to make now, changing or removing the extends resource breaks that. I did try your for loop, it will not access the cost per part that way as ingredient is just an integer. Will keep trouble shooting I wanna say I’m close but yeah.

Follow up reply to try and explain what’s happening. The _init() function as is is only reading the base class variables I.E. if I put placeholders in the array it will only read the placeholders of the base class not what I’ve since changed them to in the actual resource. At this point I feel like I’ve just wasted my time on this and that I just don’t know how to make a custom resource even though I know I’ve done stuff similar to this before. I’ve looked at my previous code and I still don’t get what I’m doing wrong it just will not register that this is resource has been changed and does not have the same values as the base class.

“i”/“ingredient” should not be an integer here unless you iterate over ingredients.size() instead of over the array or your array is filled with ints. My code example was not “for ingredient in ingredients.size()” but “for ingredient in ingredients”.

If you feel like its too difficult try to make your code simpler. As mentioned, I see a lot of examples of completely unnecessary lines that does nothing or lines that actively invite bugs into your code or make it more difficult to read. No wonder it makes it difficult to work on it.

The second if check here is a complete waste for example, just making it a mess to read.

for i in ingredients: (You ask if ingredients.size > 0)
	if ingredients.size() > 0: (You again ask if ingredients.size > 0)

you were right my code was unnecessarily complicated. Replacing it with what you have typed though still will not work. It still completely ignores the specific resources ingredient array and just treats it as if the resource I made has all the default values. I think the issue lies more between how export variables are treated and when the _init function is run. This is what my current ProductClass Script looks like and what the Test Script prints.

extends Resource

class_name Product

@export var temp : String
@export var ingredients : Array 
@export var expenses : float 
@export var selling_price : float = expenses + (expenses * 0.5)

func _init() -> void:
	for ingredient in ingredients:
			expenses += ingredient.cost_per_part
			print(str(ingredients.get(ingredient).cost_per_part))

Hot
[(res://ingredients/espresso.tres):<Resource#-9223372001958165047>, (res://ingredients/espresso.tres):<Resource#-9223372001958165047>]
0.0
0.0

I want it to print:

Hot
[(res://ingredients/espresso.tres):<Resource#-9223372001958165047>, (res://ingredients/espresso.tres):<Resource#-9223372001958165047>]
1.5
2.25

I do apologize for being confusing at any point. I have only ever worked with the hand hold of tutorials before, this is my first attempt at just coding without having to copy someone else for every line.

OK, I am a bit tired so I won’t check anything too closely, but i think you should perhaps just give up in _init() for now. Just create a separate function “calculate_total_cost()” or something, and call it when you need to.

If a problem is too frustrating and annoying, sometimes its better to just try a quick fix to get rid of it.

Yeah at this point I’m realizing the _init function just does not work how I want it to, unfortunately for me. I do wanna thank you for looking at it at all. Wish I would’ve had this realization before making the post.

I checked and yes, it is true! The script will set variables to their exported values after _init(). So you have to postpone the adding loop until after init.
Either way, no reason to feel like any of this was a waste of time. You probably learned a lot from these problems. I learned more about init because of this at least.

Yep, creating a custom set_variables function did work though and should be fine with how I want to actually implement the products in my game, so I guess no harm no foul. That is also very true! I have at the very least learned how the init function works even if it doesn’t work the way I wanted it to. Thank you again, I do not have people who are interested in code in my real life so the forum is one of the only places I can go to to figure this stuff out so any replies/help is greatly appreciated.