0
\$\begingroup\$

I have been wondering how I can place a bowl on a campfire in Unity using C#, similar to how it is done on Green Hell.

I currently have an inventory system set up where you can equip the item in your hands from the hotbar.

The reason I am asking this is because my current brute force method is to have the campfire find the player's bowl with GameObject.Find after it has been instantiated. The player can then press E at the campfire to place it on it.

It would obviously be silly to have the campfire find the bowl and any other item that is capable of going onto the campfire like meat or wood etc., so I'm wondering what would be a more scalable way to have this work with multiple items.

\$\endgroup\$
3
  • \$\begingroup\$ Why would you have the campfire find the bowl? It seems more logical to have the bowl find the campfire when you press E. If you want to highlight that the bowl can be placed on the campfire before the player presses E, use a raycast from the player to see if there is a campfire in front of the player. \$\endgroup\$
    – Kevin
    Sep 8 at 17:09
  • \$\begingroup\$ Thanks, I'll give that a go :) \$\endgroup\$
    – Skourge
    Sep 8 at 17:22
  • \$\begingroup\$ I guess I had the campfire as an IInteractable, so all the logic was on the campfire. \$\endgroup\$
    – Skourge
    Sep 8 at 17:25

1 Answer 1

0
\$\begingroup\$

The item being held by the player is a property of the player, so extend your player class to have a

public GameObject currentlyHeldObject;

And make sure your inventory system sets it as appropriate (or set it to null if your hands are empty).

Then from your campfire script, find the player once at startup and keep a reference.

MyPlayerController player;
void Awake() {
    player = GameObject.Find(...).GetComponent<MyPlayerController>();
}

In future your fire can reference player.currentlyHeldObject

\$\endgroup\$
2
  • \$\begingroup\$ In the context of Unity, rather than add this to a player class, I'd recommend creating an Inventory component that's solely responsible for managing held/carried items and their interactions, and separated from all the other stuff players do like move or have health. This use of composition also helps you adhere to the single-responsibility principle, so each is class leaner. easier to maintain and keep bug-free. And if later you need NPCs to hold items, they can! \$\endgroup\$
    – DMGregory
    Sep 8 at 21:13
  • \$\begingroup\$ Thanks for all the help, yep this was what I was looking for, the campfire to find all objects summed into one variable. \$\endgroup\$
    – Skourge
    Sep 9 at 2:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .