Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Getting a variable form another script on another object.

Discussion in 'Getting Started' started by Garcia-Rojas, Sep 7, 2015.

  1. Garcia-Rojas

    Garcia-Rojas

    Joined:
    Sep 1, 2015
    Posts:
    16
    Hello everyone!

    I know this thread has been posted a thousand times but i promise i can't solve it. I found a lot of information and i cant even think about it anymore so I ask for a bit of help.

    Is even simple than any other thing. I have 2 objects, and 2 diferent Script atached to each one.
    Could someone tell me how to access to one variable from Script1 and use it in Script2?
    I've read the GetComponent() and read many other post and now im even more confused...

    Truly thanks in advance.
     
  2. jhocking

    jhocking

    Joined:
    Nov 21, 2009
    Posts:
    813
    If you are familiar with OOP, think of each script like a class, and each script component on an object like an instance of that class. (think of it like that because that's what's happening :p)

    That means your Script2 needs to have a reference to Script1 (or at least to the object with Script1 attached). There are multiple ways to do that, with the simplest being to create a public variable in Script2 that is of type Script1, and then drag the object onto that variable in the Inspector.

    I don't know exactly which of the dozens of scripting tutorials shows this process, but I am sure one of them does.
     
  3. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,943
  4. Garcia-Rojas

    Garcia-Rojas

    Joined:
    Sep 1, 2015
    Posts:
    16
    #2 #3 Okay, You know that feel like you are the most stupid human on the earth? Well I won the prize. Now i pressed "play". Everything is working...