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

how do you call a method from a script on a different gameObject?

Discussion in 'Scripting' started by deathbydragon, Mar 4, 2016.

  1. deathbydragon

    deathbydragon

    Joined:
    Mar 4, 2016
    Posts:
    54
    I have a kind limited background in coding, mostly in java, and the way I was taught to get private values from a class is to use a getter method, such as:

    public class Example {
    private int x = 0;

    public int getX() {
    return x;
    }
    }

    and other methods would call that with an instance of example like:

    Example e = new Example();
    int y = e.getX();

    however, I have no idea how to do something comparable in Unity. I have a private bool on one script on a gameObject, and I want another gameObject to be able to check that bool. Any solutions?
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
  3. deathbydragon

    deathbydragon

    Joined:
    Mar 4, 2016
    Posts:
    54
  4. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    You need to use the getComponent<>()
    e.getComponent<ScriptA>().getX();

    and change Example e to,
    public GameObject e;

    So what you need is a variable to store the gameObject,
    gameObject e has a script attached to it named ScriptA.
    Then we use the getComponent to get or set.
     
    ericbegue likes this.
  5. bishop87

    bishop87

    Joined:
    Jun 25, 2014
    Posts:
    13
    One method is to have the script script you want called on an object, and then have your caller script reference the object and then call the function

    Lets say object "CircleButt" has a script on it called CallMe
    Code (csharp):
    1.  
    2. public class CallMe : Monobehaviour {
    3. public void CallThisFunction ()
    4.         {
    5.           Debug.Log("I've been called!");
    6.         }
    7. }
    8.  


    Code (csharp):
    1.  
    2. public class SomeScript : Monobehaviour {
    3. public void SomeFunction ()
    4.           {
    5.             GameObject objectsearch = GameObject.Find("CircleButt");
    6.             objectsearch.GetComponent<CallMe>().CallThisFunction();
    7.           }
    8. }
    9.  
    GameObject.Find isn't always the best option to use, but it is an option.