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

Communicating between scripts on the same game object

Discussion in 'Scripting' started by UNDERHILL, Jul 10, 2014.

  1. UNDERHILL

    UNDERHILL

    Joined:
    Jul 6, 2014
    Posts:
    9
    Hello

    I have a large number of code-generated objects and I need for their scripts to talk to one another.

    Here's my attempt that isn't working right, can someone please help?

    EDIT: The below works. I figured it out somehow so now here's an example for searchers;

    onescript.js
    Code (javascript):
    1.  
    2. #pragma strict
    3. public var testvar : String = "the blue manatee flies at midnight";
    4. function Start () { };
    5. function Update () { };
    6.  

    twoscript.js
    Code (javascript):
    1.  
    2. #pragma strict
    3. function Start () {};
    4. function Update ()
    5. {
    6.  
    7. var ThisObject : GameObject = this.gameObject; //if you want to access the scripts of another object us that object
    8. var OtherScript = ThisObject.GetComponent( onescript );
    9.  
    10. var GetText : String = OtherScript.testvar;
    11.  
    12. Debug.Log(GetText);
    13. };
    14.  
    I've tried several syntax changes and I'm just not getting it right. Can someone please assist?

    thank you
     
    Last edited: Jul 10, 2014
    Arunraj likes this.
  2. UNDERHILL

    UNDERHILL

    Joined:
    Jul 6, 2014
    Posts:
    9
    OK so I did something which I can't discern and now it works! So I'm going to edit the original post to serve as an example for searchers. I searched far and wide and couldn't find a plain example that worked for me.

    See also sendmessage:

    // Calls the function ApplyDamage with a value of 5
    gameObject.SendMessage ("ApplyDamage", 5.0);

    // Every script attached to the game object
    // that has an ApplyDamage function will be called.
    function ApplyDamage (damage : float) {
    print (damage);
    }
     
    Last edited: Jul 10, 2014
  3. Arunraj

    Arunraj

    Joined:
    Jul 4, 2012
    Posts:
    21
    hello UNDERHILL, please mark its as solved in tittle. so it gives better reachable