I have three scripts, player, item and box. I want to store the item in the box but but i want to check if the item in the players hand is an item that can be stored.
player - script
object_in_hand = null
item - script (is a resource with an export of storable_object bool set true in the inspector)
func _ready():
item_res = preload("res://Scripts/Resources/items.tres") as Items
func pick_up_object():
if ltem_res.storable_object:
player.object_in_hand = self
Box - script ( storable_items is a bool = ltem_res.storable_object)
func place_item_in_container():
#if the item is in the players hand is a storable object
if player.object_in_hand and storable_items:
pass
The above is incorrect and doesnt do what my brain wants it to do. As above I want check if the item in the players hand is an item that can be stored. if it is then store it.
I cant get my head round checking the rigibody2d node in hand with a bool on the item stating, yes this is true it can be stored.
Lets say the player can only hold one item in his hand, and the box already knows the player (it seems like that in your box code).
Now all that is left is checking these conditions:
does the player have an item in his hand
is the item that the player have in this hand storable
We can do both checks in one line:
func place_item_in_container() -> void:
if player.object_in_hand and player.object_in_hand.storable_object:
# place the item in the container here
# example:
#items_in_container.append(player.object_in_hand)
#player.object_in_hand = null
If you want this a bit more sorted out, have a look at this:
func place_item_in_container() -> void:
var hand_object = player.object_in_hand
var player_has_object: bool = hand_object != null
if not player_has_object:
# player has nothing in his hands
return
var object_is_storable: bool = hand_object.storable_object
if not object_is_storable:
# we cannot add this item
return
# place the item in the container here
I’m a bit confused - why are you checking whether the object has the method “is_storable”? Are you assuming that the player can have objects in his hand that don’t have the script on it?
Also in this you’re missing to actually call the method:
if item and item.has_method("is_storable") and item.is_storable():
If you use a custom type for Item that has a property var is_storable: bool = false then it can simplify things a bit because you can guarantee that all items have an is_storable value.
For example the function on your Box could be something like this:
func place_in_container(item: Item):
if item.is_storable: # Since you can only pass items into this func, this var is guaranteed to exist
# Store in Box