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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Getting variable from other script

Discussion in 'Scripting' started by MorkisLTU, May 25, 2016.

  1. MorkisLTU

    MorkisLTU

    Joined:
    May 25, 2016
    Posts:
    1
    Hello,
    i'm new to unity so i have question how can i take variable from other script. I'm with friends making game with maze for project. We have Maze script to generate integer array for maze, Monster script to move monster in maze and GameManager to initialize game. Maze is generated in GameManager using Maze object and i want to get it for my Monster script. But it should be the same array so monster could walk properly.
     

    Attached Files:

  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    You should always post the code instead of uploading it using [CODE][/CODE] tags, because if @BoredMormon is on his phone, then he can't help and that would be a shame, wouldn't it?
    Generally, like in C# you could just simply pass the instance of the main class to all of the script's needing it, so for example:
    Code (CSharp):
    1. YourClassTypeHere getYourClassType () {
    2.     return this;
    3. }
    and then when you have public variables, you could simply:
    int mazeSize = yourScriptInstanceHere.yourVariableName;
     
  3. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
    Try using something like on your maze script:
    Code (CSharp):
    1. public MonsterScript mS;
    2.  
    3. mS = GameObject.Find("MonsterObject").GetComponent<MonsterScript>();
    Then just call:
    Code (CSharp):
    1. mS.DoSomething();
    If you can just assign mS in the inspector, if not using GameObject.Find() in start is fine. :)
     
  4. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108