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 Reading variables from another script?

Discussion in 'Scripting' started by DrJkJones, Jul 23, 2023.

  1. DrJkJones

    DrJkJones

    Joined:
    Jan 9, 2022
    Posts:
    21
    Hi, frankly I'm surprised this hasn't come up before for me, but how would I go about reading a variable from another script? Currently I've got an API call that generates a story on one script, and input fields that take in character names, an antagonist, and a contagonist and store them as strings on another script. What I'm trying to do is take those strings and pass them into the API's URI so that the user can customize the characters for the story. I've got some screenshots attached too that might help. Thank you!
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    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.
     
  3. DrJkJones

    DrJkJones

    Joined:
    Jan 9, 2022
    Posts:
    21
    Thanks! It worked perfectly!
     
    Kurt-Dekker likes this.