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

Need help acessing variable from different script.

Discussion in 'Scripting' started by SAMM1T_, Sep 13, 2021.

  1. SAMM1T_

    SAMM1T_

    Joined:
    Aug 13, 2021
    Posts:
    10
    Hi all, I need to acess a bool variable from another script/class to test it in an if() statment.

    Code (CSharp):
    1.  
    2. public class ExampleOne
    3. {
    4.     public bool b = true;
    5. }
    6.  
    7. // the class on the other script
    8. public class ExampleTwo
    9. {
    10.     if(b == true)
    11.     {
    12.         //do something
    13.     }
    14. }
    15.  
    I must note that the scripts are atteched to 2 different game objects, but these game objects are under the same parent game object.
    And
    Code (CSharp):
    1.  public bool b = true;
    cannot be a static variable as the value needs to be able to change.

    I hope all of this makes sense, I've been stuck on this for a while now and have kept putting it off as I cannot find a soloution.
     
  2. UncleanWizard

    UncleanWizard

    Joined:
    Jun 5, 2021
    Posts:
    38
    Use the "." accessor which is given by almost every programming languages.

    You can use methods like GameObject.Find or FindObjectOfType to get the gameobject you want to get the class from. Then you can use the GetComponent method.

    Code (CSharp):
    1. var objToGetB = GameObject.Find("nameofobject");
    2. // You can also use gameObject.FindObjectOfType<YourClass>() to get the class itself directly.
    3. // You can also use GameObject.FindWithTag("tag");
    4.  
    5. // Then
    6. var myClass = objToGetB.GetComponent<YourClass>()
    7.  
    8. myClass.yourField// use it however you like
    9.  
    10.  
    You can find more in methods here: https://docs.unity3d.com/ScriptReference/GameObject.html in the static methods section.
     
    Last edited: Sep 13, 2021
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,717
  4. SAMM1T_

    SAMM1T_

    Joined:
    Aug 13, 2021
    Posts:
    10