Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How can I call a function from a nearby gameobject's script?

Discussion in 'Scripting' started by jleven22, Oct 6, 2023.

  1. jleven22

    jleven22

    Joined:
    Mar 26, 2019
    Posts:
    397
    I have some shop items and a shop NPC.

    The shop items are instantiated randomly. When items are purchased, I want to call an animation from the shop NPC.

    How can I access the NPC script and call that animation from an instantiated gameobject?

    I thought about calling accessing the shop item scripts from the NPC when they're instantiated, but it doesn't make as much logical sense.

    Any help is appreciated!
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,593
    When you Instantiate the object, why not just give them a reference to the NPC?
     
  3. jleven22

    jleven22

    Joined:
    Mar 26, 2019
    Posts:
    397
    I guess I'm wondering how to.

    To clarify, there will be more than one instance of this NPC (shows up in several places in the scene). Other than making it public static, I'm not sure how to reference the nearest version of the NPC.
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,843
    This just needs to be handled by some top-level component, probably the one randomly instantiating these items?

    Ergo, when they're instantiated, it subscribes a method to a delegate on the item's component. When an item is bought, it fires the delegate. Said top level component can just reference the NPC, and start up the animation.
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    If you want to reference a nearby object one of the best approaches is to use the physics engine. Within that there are two main approaches here. One option is to use a trigger collider on the NPC. You can then have the player keep track of which NPCs (or ANY interactable objects) it is nearby, and interact with them. For example I recommend creating an Interactable component which you can attach to your NPC, as well as a sphere trigger collider of a size of your choosing:

    Code (CSharp):
    1. public class Interactable : MonoBehaviour {
    2.   [SerializeField] UnityEvent OnInteract;
    3.  
    4.   public void Interact() {
    5.     OnInteract.Invoke();
    6.   }
    7. }
    Then on your player you can use OnTriggerEnter/Exit to detect interactables and interact with them when the player presses a key:

    Code (CSharp):
    1. List<Interactable> nearbyInteractables = new();
    2.  
    3. void OnTriggerEnter(Collider other) {
    4.   if (other.TryGetComponent(out Interactable interactable) {
    5.     nearbyInteractables.Add(interactable);
    6.   }
    7. }
    8.  
    9. void OnTriggerExit(Collider other) {
    10.   if (other.TryGetComponent(out Interactable interactable) {
    11.     nearbyInteractables.Add(interactable);
    12.   }
    13. }
    14.  
    15. void Update() {
    16.   if (nearbyInteractables.Count > 0 && Input.GetKeyDown(KeyCode.E)) {
    17.     nearbyInteractables[0].Interact();
    18.   }
    19. }
    You can expand this to show some UI like "press E to talk" when nearby the NPC for example.

    Another option besides using OnTriggerEnter/Exit is to use Physics.OverlapSphere near yout player and look for any colliders nearby that also have the Interactable component on them.
     
    jleven22 and Nad_B like this.
  6. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    326
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Your question embodies at least three different fundamental Unity beginner concepts, all completely unrelated to each other. I'm not sure which of these you're having issues with, but basically:

    1. How to find a particular NPC you're close to or looking at. See what @Nad_B posted or any one of ten billion other similar videos. This is well-solved well-described territory.

    2. How to spawn stuff and keep a reference to it: Instantiate<T>() returns a reference to what you spawn. Use that reference. That's why Unity gives it to you. Do not spawn things blindly into the scene, then go looking for it with Find / Get. That approach does not make logical sense.

    3. How to access things (call methods, access fields) on other instances. This is just basic Unity inter-object signaling / messaging. The basics are posted below:

    Referencing variables, fields, methods (anything non-static) in other script instances:

    https://forum.unity.com/threads/hel...-vars-in-another-script.1076825/#post-6944639

    https://forum.unity.com/threads/accessing-a-gameobject-in-different-scene.1103239/

    It isn't always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

    Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

    That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.


    ---------------------

    I'll also tack this on as it appears this is part of some kind of inventory / NPC shop system:

    These things (inventory, shop systems, character customization, dialog tree systems, crafting, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.

    Inventory code never lives "all by itself." All inventory code is EXTREMELY tightly bound to prefabs and/or assets used to display and present and control the inventory. Problems and solutions must consider both code and assets as well as scene / prefab setup and connectivity.

    Inventories / shop systems / character selectors all contain elements of:

    - a database of items that you may possibly possess / equip
    - a database of the items that you actually possess / equip currently
    - perhaps another database of your "storage" area at home base?
    - persistence of this information to storage between game runs
    - presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
    - interaction with items in the inventory or on the character or in the home base storage area
    - interaction with the world to get items in and out
    - dependence on asset definition (images, etc.) for presentation

    Just the design choices of such a system can have a lot of complicating confounding issues, such as:

    - can you have multiple items? Is there a limit?
    - if there is an item limit, what is it? Total count? Weight? Size? Something else?
    - are those items shown individually or do they stack?
    - are coins / gems stacked but other stuff isn't stacked?
    - do items have detailed data shown (durability, rarity, damage, etc.)?
    - can users combine items to make new items? How? Limits? Results? Messages of success/failure?
    - can users substantially modify items with other things like spells, gems, sockets, etc.?
    - does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
    - etc.

    Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

    Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

    Breaking down a large problem such as inventory:

    https://forum.unity.com/threads/weapon-inventory-and-how-to-script-weapons.1046236/#post-6769558

    If you want to see most of the steps involved, make a "micro inventory" in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).

    Everything you learn doing that "micro inventory" of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.

    Breaking down large problems in general:

    https://forum.unity.com/threads/opt...n-an-asteroid-belt-game.1395319/#post-8781697

    The moment you put an inventory system into place is also a fantastic time to consider your data lifetime and persistence. Create a load/save game and put the inventory data store into that load/save data area and begin loading/saving the game state every time you run / stop the game. Doing this early in the development cycle will make things much easier later on.
     
    Last edited: Oct 7, 2023
  8. jleven22

    jleven22

    Joined:
    Mar 26, 2019
    Posts:
    397
    Wait actually I like the idea of using a collider. Simple and easy to do. Good thinking!