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 can i call a function of script1.cs from script2.cs

Discussion in 'Scripting' started by jessica1986, May 29, 2013.

  1. jessica1986

    jessica1986

    Joined:
    Feb 7, 2012
    Posts:
    621
    This is my script, i wanna call SpawnBottle( BottleDirection.RIGHT ); from other script, how can i do it ??

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5. public class BottleThrowPointController : MonoBehaviour
    6. {
    7.    
    8.        int requiredTapCount = 1;
    9.     private int leftyes = 0;
    10.  bool tappedOnLeft;
    11.     bool pause = false;
    12.    
    13.    
    14.    
    15.    
    16.    
    17.    
    18.        
    19.         void OnEnable()
    20.         {
    21.                 FingerGestures.OnFingerTap += FingerGestures_OnFingerTap;
    22.                
    23.        
    24.         }
    25.  
    26.         void OnDisable()
    27.         {
    28.                 FingerGestures.OnFingerTap -= FingerGestures_OnFingerTap;
    29.                
    30.         }
    31.    
    32.         IEnumerator Tcounter (){
    33.         //Debug.Log("inside counter");
    34. yield return new WaitForSeconds(0.3f);
    35. Debug.Log("0.3 secs..");       
    36. SpawnBottle( BottleDirection.RIGHT );
    37.         yield return new WaitForSeconds(0.3f);
    38. Debug.Log("0.3 secs..");       
    39. SpawnBottle( BottleDirection.RIGHT );
    40. }
    41.  
    42.         void FingerGestures_OnFingerTap( int fingerIndex,  Vector2 fingerPos, int tapCount )
    43.         {
    44.                 //HAVE FUN HERE!
    45.          if( tapCount >= requiredTapCount )
    46.             if (!rect_inventory.Contains( new Vector2(fingerPos.x, Screen.height - fingerPos.y + 1))) {
    47.         {
    48.             Debug.Log( "Tapcount: " + tapCount );
    49.             if ( fingerPos.x > Screen.width/2 ){
    50.                 tappedOnLeft=false;
    51.                 Debug.Log("its tapped on right");
    52.                 SpawnBottle( BottleDirection.RIGHT );
    53.                    
    54.                     StartCoroutine (Tcounter());
    55.                    
    56.                    
    57.             }
    58.             else{
    59.                 tappedOnLeft=true;
    60.                 Debug.Log("its tapped on left");
    61.                 SpawnBottle( BottleDirection.LEFT );
    62.                    
    63.             }
    64.         }
    65.         }
    66.     }
    67.    
    68.        
    69.         void Start(){
    70.                 //PlayerPrefs.DeleteAll();
    71.                 Load_powerup_1_1();
    72.                 //Debug.Log(bought_toggle_val_powerup_1_1);
    73.         }
    74.        
    75.        
    76.          
    77.     public   bottleMovement[] bottles; // list of bottles to instantiate
    78.    
    79.          public GUIStyle Inv_button;
    80.          Rect rect_inventory = new Rect(Screen.width*93/100, Screen.height*1/100, Screen.width/12, Screen.height/8);
    81.        
    82.         public GUIStyle inv_main_window_button;
    83.         public GUIStyle inv_main_window;
    84.      //Rect rect_inv_main_window = new Rect(Screen.width*10/100, Screen.height*10/100, Screen.width-Screen.width*20/100, Screen.height-Screen.height*20/100);
    85.          Rect rect_inv_main_window = new Rect(100,100,200,200);
    86.         //Rect rect_inv_main_window = new Rect(hosizontal position,vertical position,size-horizontal,size vertical);
    87.         public Vector2 scrollPosition;
    88.         float scrollSpeed = 3;
    89.        
    90.        
    91.          public GUIStyle toggle_style;
    92.         private bool toggle_val = false;
    93.         bool open_Inventory_Window = false;
    94.        
    95.        
    96.         public static int toggle_val_powerup_1_1=10;
    97.                 public static bool bought_toggle_val_powerup_1_1=false;
    98.         public static string save_powerup_1_1;
    99.        
    100.        
    101.         void OnGUI(){
    102.                
    103.                 //Debug.Log(toggle_val);
    104.                //  GUI.skin.button = Inv_button;
    105.                  //GUI.skin.window = inv_main_window;
    106.                
    107.                
    108.                
    109.                 // this button is just used to show the image and nothing else
    110.         if (GUI.Button(new Rect(Screen.width*93/100, Screen.height*1/100, Screen.width/12, Screen.height/8), "")){
    111.             Debug.Log("Clicked the button with text");
    112.                 }
    113.                 GUI.Box(rect_inventory, "someText");
    114.                
    115.                 if(open_Inventory_Window==true)
    116.                         rect_inv_main_window = GUI.Window(2, rect_inv_main_window, DoMyWindow2, "");
    117.                
    118.                 //main Inventory power up window
    119.                
    120.                
    121.                
    122.         }
    123.        
    124.        
    125.        
    126.         // Update is called once per frame
    127.         void Update ()
    128.         {
    129.                
    130.                 scrollPosition.x += Input.GetAxis("Horizontal") * scrollSpeed;
    131.         scrollPosition.y -= Input.GetAxis("Vertical") * scrollSpeed;
    132.                
    133.                 if (!rect_inventory.Contains( new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y + 1))) {
    134.                         if (Input.GetMouseButtonDown(2) Time.timeScale!=0)
    135.                                  {
    136.                        
    137.                         if ( Input.mousePosition.x > Screen.width/2 )
    138.                                 SpawnBottle( BottleDirection.RIGHT );
    139.                         else
    140.                                 SpawnBottle( BottleDirection.LEFT );
    141.                                 Debug.Log("outside rect");
    142.                
    143.         }
    144.                        
    145.                        
    146.                 }
    147.        
    148.                 else if (rect_inventory.Contains( new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y + 1))) {
    149.            
    150.                 if (Input.GetMouseButtonDown(0) pause==false){
    151.                                 Time.timeScale = 0.0f; // paused the game
    152.                                 Debug.Log("inside rect");
    153.                                 pause=true;
    154.  
    155.                         }
    156.             else if (Input.GetMouseButtonDown(0)  pause==true){
    157.                                 Time.timeScale = 1.0f; // paused the game
    158.                                 Debug.Log("inside rect2");
    159.                                 pause=false;
    160.  
    161.                         }
    162.         }
    163.                
    164.                
    165. //                if (Input.GetMouseButtonDown(0))
    166. //                {
    167. //                    
    168. //                        if ( Input.mousePosition.x > Screen.width/2 )
    169. //                                SpawnBottle( BottleDirection.RIGHT );
    170. //                        else
    171. //                                SpawnBottle( BottleDirection.LEFT );
    172. //                
    173. //        }
    174.                
    175.         }
    176.        
    177.          void SpawnBottle( BottleDirection direction )
    178.         {
    179.                 //as the prefab is of type BottleMovement, it'll return a BottleMovement
    180.                 bottleMovement newBottle = Instantiate(bottles[0],transform.position, Quaternion.identity)as bottleMovement;
    181.                
    182.                
    183.                
    184.                 //set the side it shall move
    185.                 newBottle.direction = direction;
    186.         }
    187.        
    188.        
    189.          void DoMyWindow2(int windowIDE) {
    190.                 // scrollPosition = GUI.BeginScrollView(rect_inv_main_window, scrollPosition, new Rect(Screen.width*5/100, Screen.height*5/100, Screen.width-Screen.width*15/100, Screen.height-Screen.height*15/100));
    191.                
    192.                 scrollPosition = GUI.BeginScrollView(new Rect(10,20,rect_inv_main_window.width*0.9f, rect_inv_main_window.height - 20), scrollPosition, new Rect(0, 0, 50,Screen.height));
    193.                 //  scrollPosition = GUI.BeginScrollView(new Rect(10,20,rect_inv_main_window.width * 0.5f, rect_inv_main_window.height - 40), new Vector2(scrollPosition.x, MyTouchInput.touchPosition.y), new Rect(0, 0, 50,Screen.height));
    194.                // GUI.skin.button = inv_main_window_button;
    195.                
    196.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*20/100+10, 20, 20), "x1");
    197.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*30/100+10, 20, 20), "x2");
    198.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*40/100+10, 20, 20), "x3");
    199.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*50/100+10, 20, 20), "x4");
    200.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*60/100+10, 20, 20), "x5");
    201.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*70/100+10, 20, 20), "x6");
    202.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*80/100+10, 20, 20), "x7");
    203.         //              GUI.Button(new Rect(Screen.width*20/100, Screen.height*80/100+10, 20, 20), "x8");
    204.          // close button
    205. //                if (GUI.Button(new Rect(0, 10, 20, 20), "x")){
    206. //                        open_Inventory_Window=false;
    207. //                        Time.timeScale = 1.0f;}
    208.             Debug.Log("Clicked the button with text");
    209.            
    210.                 GUI.Button(new Rect(0, 10, 100, 40), "x1");
    211.         GUI.Button(new Rect(0, 60, 100, 40), "x2");
    212.         GUI.Button(new Rect(0, 110, 100, 40), "x3");
    213.         GUI.Button(new Rect(0, 160, 100, 40), "x4");
    214.         GUI.Button(new Rect(0, 210, 100, 40), "x5");
    215.         GUI.Button(new Rect(0, 260, 100, 40), "x6");
    216.         GUI.Button(new Rect(0, 310, 100, 40), "x7");
    217.  
    218.                 GUI.EndScrollView();
    219.             if (GUI.Button(new Rect(Screen.width*75/100+10, Screen.height*70/100+10, 20, 20), "x")){
    220.                         open_Inventory_Window=false;
    221.                         Time.timeScale = 1.0f;
    222.             Debug.Log("Clicked the button with text");
    223.                
    224.                
    225.                
    226.                 }
    227.                 // 114 - 129 code for toggle
    228. //              GUI.skin.toggle = toggle_style;
    229. //            
    230. //              // step1::  disable it, and only enable it if highscore [total coins] value is greater than 200
    231. //              GUI.enabled=false;
    232. //              Debug.Log(bought_toggle_val_powerup_1_1);
    233. //              if(scoreHandler._highscore>toggle_val_powerup_1_1  bought_toggle_val_powerup_1_1==false){
    234. //              GUI.enabled=true;      
    235. //                      if(toggle_val==true){
    236. //                              Debug.Log(toggle_val);
    237. //                              bought_toggle_val_powerup_1_1=true;
    238. //                              GUI.enabled=false;
    239. //                              Save_powerup_1_1();
    240. //                      }
    241. //            
    242. //              }
    243. //                toggle_val = GUI.Toggle(new Rect(10, 10, 25, 25),toggle_val, "");
    244.        
    245.     }
    246.        
    247. //              public static void Save_powerup_1_1(){
    248. //PlayerPrefs.SetInt("save_powerup_1_1", bought_toggle_val_powerup_1_1 ? 1 : 0);
    249. //}
    250.        
    251.  
    252. //      public static void Load_powerup_1_1(){
    253. //              bought_toggle_val_powerup_1_1 = PlayerPrefs.GetInt("save_powerup_1_1")  == 1 ? true : false;
    254. //      }
    255.        
    256.           public static void SetBool(string Name, bool value)
    257.     {
    258.         PlayerPrefs.SetInt(Name, value ? 1 : 0);
    259.     }
    260.  
    261.      public static bool GetBool(string Name, bool _default = false)
    262.     {
    263.         if (PlayerPrefs.HasKey(Name))
    264.         {
    265.             return PlayerPrefs.GetInt(Name) == 1;
    266.         }
    267.         return _default;
    268.     }
    269.  
    270. public static void Save_powerup_1_1(){
    271. SetBool("save_powerup_1_1", bought_toggle_val_powerup_1_1);
    272. }
    273.        
    274.         public static void Load_powerup_1_1(){
    275.                 bought_toggle_val_powerup_1_1 = GetBool("save_powerup_1_1");
    276.         }
    277. }
     
  2. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    seriously? How have you not had to do this already...


    why dont you go do a tutorial. This is like Unity 101.
     
  3. arkon

    arkon

    Joined:
    Jun 27, 2011
    Posts:
    1,122
    Code (csharp):
    1. ReturnedValue = OtherGameObject.GetComponent<OtherScript>().OtherFunction(Parameters to pass);
     
  4. KaBKa

    KaBKa

    Joined:
    May 20, 2013
    Posts:
    34
    ..... Lol What forum are you on again?

    He is right though you should have already known how to do this. So assuming you know how to use google i will try to help by saying you forgot to make spawnBottles a public function. Which is what i am hoping is making the solutions you found by googling it not work.
     
  5. ExpiredIndexCard

    ExpiredIndexCard

    Joined:
    Mar 24, 2013
    Posts:
    105
  6. KaBKa

    KaBKa

    Joined:
    May 20, 2013
    Posts:
    34
  7. Jtbentley_v2

    Jtbentley_v2

    Joined:
    Sep 5, 2012
    Posts:
    174
    Ideally you should have the component pre-cached anyway (GetComponents at run time are frowned upon once it comes to optimisation).

    But basically, you can store a variable that points to that other component and access it like you would a normal component (transform, audio, etc).

    otherBottle.SpawnBottle(BottleDirection.RIGHT);

    Just so long as otherBottle is declared previously as the component name. You can either link it in your awake or in the inspector.
     
  8. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    I think im on the 'spoon feed answers because they were too lazy to do a tutorial or a quick search on google first' forum...

    ;)
     
  9. ExpiredIndexCard

    ExpiredIndexCard

    Joined:
    Mar 24, 2013
    Posts:
    105
    Get component is very expensive in terms of processing . Send message is less expensive and a lot easier too.
     
  10. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    And this is based off what exactly? Feels like an ass-pluck
     
  11. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    Do you have any hard data to pack up that assertion? Intuitively, for me at least, GetComponent should be less costly than SendMessage.

    EDIT:

    A reply along those lines was my first impulse :D
     
  12. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,182
    Is based off that package of index cards I bought and never opened after finding that cool Notes app.
     
  13. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    So I threw this together (possibly not the correct way to test this sort of thing..meh), but it still gave me some interesting (and expected) results.

    You can see for yourself, but from my tests, cached fastest, GetComponent 2nd, SendMessage 3rd


    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class PerformanceTest : MonoBehaviour {
    6.    
    7.    
    8.     public float time1 = 0;
    9.     public float time2 = 0;
    10.     public float time3 = 0;
    11.    
    12.     public int count = 0;
    13.    
    14.     public int testIndex = 0;
    15.     public int iterations = 100000;
    16.     public int max = 10000000;
    17.    
    18.     public PerformanceTest instance;
    19.    
    20.     void Start()
    21.     {
    22.         instance = (GetComponent(typeof(PerformanceTest)) as PerformanceTest); 
    23.     }
    24.    
    25.     void Check()
    26.     {
    27.         count++;
    28.         if(count == max)
    29.         {
    30.             testIndex++;
    31.             count = 0;
    32.         }
    33.     }
    34.    
    35.     void Test1()
    36.     {
    37.         instance.Test();
    38.         Check();
    39.     }
    40.    
    41.     void Test2()
    42.     {
    43.         SendMessage("Test");
    44.         Check();
    45.     }
    46.    
    47.     void Test3()
    48.     {
    49.         (GetComponent(typeof(PerformanceTest)) as PerformanceTest).Test(); 
    50.         Check();
    51.     }
    52.    
    53.     void Update()
    54.     {
    55.         switch(testIndex)
    56.         {
    57.         case 0:
    58.                 for(int x = 0; x< iterations;x++)
    59.                     Test1 ();
    60.                 time1 += Time.deltaTime;
    61.             break;
    62.            
    63.         case 1:
    64.                 for(int x = 0; x< iterations;x++)
    65.                     Test2 ();
    66.                 time2 += Time.deltaTime;
    67.             break;
    68.            
    69.         case 2:
    70.                 for(int x = 0; x< iterations;x++)
    71.                     Test3 ();
    72.                 time3 += Time.deltaTime;
    73.             break;
    74.            
    75.         }
    76.     }
    77.    
    78.     void Test () {
    79.         count++;
    80.     }
    81. }
    82.  
    83.  
    84.  
     
  14. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    The test looks legit to me. Thanks for taking the time to test it!
     
  15. ExpiredIndexCard

    ExpiredIndexCard

    Joined:
    Mar 24, 2013
    Posts:
    105
    It's based off my reading about these two at unity 3d.com. thanks for your concerns
     
  16. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    Would you share the link to that info? I'm not trying to be argumentative here, but rather genuinely curious.
     
  17. ExpiredIndexCard

    ExpiredIndexCard

    Joined:
    Mar 24, 2013
    Posts:
    105
    Im not sure where it is but it is part of the unity website. Search, "Unity Performance Optimizations". There should be several links. Not only will you find the things about "getcomponent", but you will find many many things that help improve your game. Its worth a look
     
  18. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    I can't find anything there supporting your original assertion that SendMessage is faster than GetComponent. It's perfectly fine with me if you prefer SendMessage for whatever reasons, but making unsupported claims like these with such authority on a forum frequented by people who are still learning and who might take your claims to heart is, in my opinion, an irresponsible thing to do.
     
  19. ExpiredIndexCard

    ExpiredIndexCard

    Joined:
    Mar 24, 2013
    Posts:
    105