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 call function in clone

Discussion in 'Scripting' started by Felix0044, Jun 7, 2023.

  1. Felix0044

    Felix0044

    Joined:
    Apr 24, 2023
    Posts:
    4
    Hi, I'm trying to call a function on clones from another script, best I've been able to achieve is calling the function in one of the clones but I want to be able to call them all at the same time since they're clones of the same game object running the same script. although I could probably call them all individually I don't want to hard code the amount of clones I can have.

    is there a way to assign all the clones automatically to the variable shown ?:



    other video I watched:
     
  2. Felix0044

    Felix0044

    Joined:
    Apr 24, 2023
    Posts:
    4
    1st video is supposed to start at 2:30
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    When you Instantiate() something it returns a reference to it.

    Use that reference to access the new clone.

    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.
     
  4. Felix0044

    Felix0044

    Joined:
    Apr 24, 2023
    Posts:
    4
    Thanks for the response, how would I access the return from the script that instantiates the clones in the script that calls the function?
     
  5. Felix0044

    Felix0044

    Joined:
    Apr 24, 2023
    Posts:
    4
    Also, with the return wouldn't I still have to create a separate variable for each clone?