Referencing an GameObject

Discussion in 'Game Development (Technical)' started by Cubee01, Dec 21, 2017.

  1. Cubee01

    Cubee01 New Member

    Joined:
    Feb 13, 2017
    Messages:
    7
    Likes Received:
    0
    Hello!

    I am pretty new to coding in c# with unity. I am wondering how you can reference an GameObject variable from one script to another? I'm made the variable public but the other script cant find it.

    Thanks!
     
  2. eatsleepindie

    eatsleepindie New Member

    Joined:
    Nov 26, 2017
    Messages:
    6
    Likes Received:
    0
    Here's a trick, but it only works if there is only going to be one instance of that script (ie. gameobject with script attached). If there is more than one you'll only ever reference one of them.

    Code:
    public static MyScript inst;
    
    void Awake() {
         inst = this;
    }
    You can then reference that script from any other script using the following:

    Code:
    MyScript.inst;
    which allows you to reference any public function or variable easily:

    Code:
    MyScript.inst.MyFunction();
     

Share This Page

  • About Indie Gamer

    When the original Dexterity Forums closed in 2004, Indie Gamer was born and a diverse community has grown out of a passion for creating great games. Here you will find over 10 years of in-depth discussion on game design, the business of game development, and marketing/sales. Indie Gamer also provides a friendly place to meet up with other Developers, Artists, Composers and Writers.
  • Buy us a beer!

    Indie Gamer is delicately held together by a single poor bastard who thankfully gets help from various community volunteers. If you frequent this site or have found value in something you've learned here, help keep the site running by donating a few dollars (for beer of course)!

    Sure, I'll Buy You a Beer