Search Unity

Script disable with foreach loop on all founded objects?

Discussion in 'Scripting' started by Slyrfecso1, Aug 20, 2015.

  1. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    Hi,

    I would like to know how can I stop looping after my <drag_mouse> disabled on all founded GameObject of tagged layer?
    If I use break, then the <drag_mouse> is disabling only on the first founded object.
    Maybe I need to use "for" cycle?

    Code (CSharp):
    1. foreach(GameObject gameObj in GameObject.FindGameObjectsWithTag("Player"))
    2.                 {
    3.                 gameObj.GetComponent<drag_mouse>().enabled = false;
    4.                 //break;
    5.                 }
    Any help will be helpful.
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    foreach is not infinite, it means "once for each of these objects", so it'll loop over all of the found objects and then it'll move on. I'm not sure what the problem is, so you'll have to be clearer.
     
  3. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    Hi,

    I try to write clearer.
    If I click a "button", then I would like to disable "drag_mouse" script on all object.
    (button = second in the upper menu)


    I got this console message:
    NullReferenceException: Object reference not set to an instance of an object
    measure.OnGUI () (at Assets/script/FINAL/measure.cs:107)


    I have made a screen-record from the problem:
    http://www.csongorfekete.com/Unity_web_player/Unity_foreach_bug_V1.mov


    This is my project, not on the final server, therefore screenshot function isn't working:
    http://www.csongorfekete.com/Unity_web_player/Terberendezo_v1.html
    - user: a
    - pass: a
    - Push Z button, then you can see debug-consol in web player


    This is the script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class measure : MonoBehaviour {
    5.  
    6.     public GUIStyle meres;
    7.     public GUIStyle merestooltip;
    8.     public GUIStyle szoveg;
    9.     public GUIStyle szovegapro;
    10.  
    11.  
    12.     public Camera cam1;
    13.     public Camera cam2;
    14.  
    15.     private string szelesseg = "";
    16.     private string hosszusag = "";
    17.  
    18.  
    19.     public Texture2D cursorTexture;
    20.  
    21.  
    22.  
    23.     public Vector2 mouse = Vector2.zero;
    24.  
    25.     int counterAT=0;
    26.     int cursorSizeX=50;
    27.     int cursorSizeY=50;
    28.  
    29.  
    30.  
    31.     void OnGUI () {
    32.      
    33.      
    34.      
    35.         if (counterAT==2)
    36.         {
    37.             counterAT = counterAT-2;
    38.             cam1.enabled = true;
    39.             cam2.enabled = false;
    40.  
    41.  
    42.         //    GameObject myCube = GameObject.FindGameObjectWithTag("Player");
    43.         //    myCube.GetComponent<tooltip>().enabled = true;
    44.         }
    45.      
    46.         if (GUI.Button (new Rect (Screen.width/2-205, 10, 50, 50), "" ,meres))
    47.         {
    48.             counterAT++;
    49.             Debug.Log(counterAT);
    50.         }
    51.      
    52.      
    53.         if (counterAT == 1)
    54.         {
    55.             GUI.Box (new Rect (20, 80, 120, 180), ""  ,merestooltip);
    56.             GUI.Label(new Rect(40, 100, 60, 25), "TÁVOLSÁG\n" +
    57.                       "MÉRÉS\n\n" +
    58.                       "Szélesség (m)\n\n\n" +
    59.                       "Hosszúság (m)" ,szoveg);
    60.  
    61.      
    62.             szelesseg = GUI.TextField (new Rect (40, 163, 60, 20), szelesseg, 4);
    63.             hosszusag = GUI.TextField (new Rect (40, 208, 60, 20), hosszusag, 4);
    64.  
    65.             mouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
    66.             GUI.DrawTexture(new Rect(mouse.x - (cursorSizeX / 2), mouse.y - (cursorSizeY / 2), cursorSizeX, cursorSizeY), cursorTexture);
    67.  
    68.             cam1.enabled = false;
    69.             cam2.enabled = true;
    70.      
    71.             GUI.Button(new Rect(40, 240, 100, 20), new GUIContent("További funkciók...",  "Pontosabb mérési\n" +
    72.                                                                   "adatokat kaphat,\n" +
    73.                                                                   "ha használja:\n\n" +
    74.                                                                   "Q = nagyítás\n" +
    75.                                                                   "W = kicsinyítés\n" +
    76.                                                                   "Jobb egér =\n" +
    77.                 "terület mozgatás"), szovegapro);
    78.             GUI.Label(new Rect(40, 270, 100, 60), GUI.tooltip , szovegapro);
    79.                  
    80.      
    81.  
    82.  
    83.  
    84.  
    85.  
    86.  
    87.  
    88.  
    89.             //         MÉRÉSI TARTOMÁNY
    90.             //        MEASURE SECTION
    91.  
    92.  
    93.             if (Input.GetMouseButton(0))
    94.                 {
    95.  
    96.                 szelesseg = mouse.x.ToString();
    97.                 hosszusag = mouse.y.ToString();
    98.  
    99.  
    100.             //        NOT FINISHED!
    101.  
    102.  
    103.  
    104.  
    105.                 foreach(GameObject gameObj in GameObject.FindGameObjectsWithTag("Player"))
    106.                 {
    107.                     gameObj.GetComponent<drag_mouse>().enabled = false;
    108.                 }
    109.                 //        break;
    110.              
    111.  
    112.  
    113.  
    114.  
    115.             //        cursorPoint++;
    116.             //        Debug.Log(cursorPoint);
    117.             //        Instantiate(cursorTexture);
    118.  
    119.  
    120.  
    121.          
    122.                 }
    123.         }
    124.     }
    125. }
    126.  



    I hope you could help me.
    Thanks.
     
  4. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    You're iterating through all objects found tagged "Player", which is working fine, but you're trying to access the "drag_mouse" component attached to each one, and not all of them have that component, apparently. You can check to see if the drag_mouse component exists by doing this:
    Code (csharp):
    1. foreach(GameObject gameObj in GameObject.FindGameObjectsWithTag("Player"))
    2. {
    3.     drag_mouse dragMouseComponent = gameObj.GetComponent<drag_mouse>();
    4.  
    5.     if(dragMouseComponent != null)
    6.     {
    7.         dragMouseComponent.enabled = false;
    8.     }
    9. }
    But I think if the different "Player" objects in your scene have different components, you probably have bigger problems.

    Btw, OnGUI is deprecated for usage other than in editor scripts, which means you shouldn't be using it at all, AND you're doing a full-scene search of objects tagged "Player" in OnGUI, which occurs multiple times per frame- that's hundreds of times per second. This is going to be painful on performance.
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Code (csharp):
    1.  
    2. if(dragMouseComponent){..}
    3.  
    I prefer the shorter version personally, does the same thing.
     
    DonLoquacious likes this.
  6. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    OnGUI isn't officially deprecated and there's no reason you can't continue to use it if it's already in your project (we do).

    If the loop is inside a button conditional then the search is only happening when the button is being pushed, not every OnGUI call. If you are spawning and destroying things in between button presses then there really isn't any other way to do it and make sure it's current.

    I hate the implicit boolean override for components. Totally not standard and completely alien unless you have a Web JS background :)

    Alternately, instead of using GameObject.Find you can use FindObjectOfType<T> and get the components directly.
     
  7. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    Thank you so much Lysander!
    It is working well with Instantiated prefab too.

    I have only one more problem:
    In the drag_mouse script I don't have Void Start, therefore the voidOnMouseDrag isn't disabling.
    If I don't use Void Start, then I don't have check box in the inspector.

    Any Idea will be helpful.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class drag_mouse : MonoBehaviour
    5. {
    6.  
    7.     private bool Triggered = false;
    8.     private bool Dragged = false;
    9.  
    10.  
    11.  
    12.  
    13.     // Use this for initialization
    14.     void Start ()
    15.     {
    16.         Dragged = true;
    17.     }
    18.  
    19.  
    20.  
    21.     Vector3
    22.         screenPoint,
    23.         offset,
    24.         scanPos,
    25.         curPosition,
    26.         curScreenPoint;
    27.  
    28.  
    29.    
    30.     void OnMouseDrag()
    31.     {
    32.  
    33.         if (Dragged)
    34.             {
    35.             if(Input.GetKeyDown(KeyCode.A))
    36.             transform.Rotate(0, 90, 0);
    37.  
    38.             if(Input.GetKeyDown(KeyCode.C))
    39.             Destroy (gameObject);
    40.  
    41.             if(Input.GetKeyDown(KeyCode.D))
    42.             Instantiate (gameObject);
    43.  
    44.     //        if(Input.GetAxis("Vertical"))
    45.     //        transform.position += new Vector3(0, 2, 0);
    46.                    
    47.             float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
    48.             Vector3 pos_move = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen ));
    49.             transform.position = new Vector3( pos_move.x, transform.position.y, pos_move.z );
    50.             }
    51.  
    52.     }
    53.  
    54.  
    55.     void OnTriggerEnter (Collider myTrigger)
    56.     {
    57.         if(myTrigger.gameObject.tag == "Player")
    58.         {
    59.             scanPos = gameObject.transform.position;
    60.             Triggered = true;
    61.             Debug.Log(name + " Triggered");
    62.         }
    63.     }
    64.  
    65.  
    66.     void OnTriggerExit (Collider myTrigger)
    67.     {
    68.         if(myTrigger.gameObject.tag == "Player")
    69.         {
    70.             Debug.Log(name + " Snap feloldása Drag alatt");
    71.             Triggered = false;
    72.         }
    73.     }
    74.  
    75.  
    76.  
    77.  
    78.     void OnMouseUp()
    79.     {
    80.         if (Triggered)
    81.         {
    82.             transform.position = scanPos;
    83.             Debug.Log(name + " Vissza az érintkezési ponthoz");
    84.  
    85.         }
    86.        
    87.     }
    88.  
    89.  
    90. }
     
  8. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    I have solved:)
    Rewrote the code:

    Now is working the disable.
    Check out my project again.
    Big thanks.


    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. class drag_mouse : MonoBehaviour
    5. {
    6.     private bool Triggered = false;
    7.     private bool dragging = false;
    8.     private float distance;
    9.    
    10.    
    11.     Vector3
    12.         screenPoint,
    13.         offset,
    14.         scanPos,
    15.         curPosition,
    16.         curScreenPoint;
    17.    
    18.    
    19.    
    20.    
    21.     void OnMouseDown()
    22.     {
    23.         if (Triggered)
    24.         {
    25.             transform.position = scanPos;
    26.             Debug.Log(name + " Vissza az érintkezési ponthoz");
    27.            
    28.         }
    29.         dragging = true;
    30.     }
    31.    
    32.     void OnMouseUp()
    33.     {
    34.         dragging = false;
    35.     }
    36.    
    37.     void Update()
    38.     {
    39.         if (dragging)
    40.         {
    41.             float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
    42.             Vector3 pos_move = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen ));
    43.             transform.position = new Vector3( pos_move.x, transform.position.y, pos_move.z );
    44.            
    45.         }
    46.     }
    47.    
    48.    
    49.     void OnTriggerEnter (Collider myTrigger)
    50.     {
    51.         if(myTrigger.gameObject.tag == "Player")
    52.         {
    53.             scanPos = gameObject.transform.position;
    54.             Triggered = true;
    55.             Debug.Log(name + " Triggered");
    56.         }
    57.     }
    58.    
    59.    
    60.     void OnTriggerExit (Collider myTrigger)
    61.     {
    62.         if(myTrigger.gameObject.tag == "Player")
    63.         {
    64.             Debug.Log(name + " Snap feloldása Drag alatt");
    65.             Triggered = false;
    66.         }
    67.     }
    68.    
    69.    
    70.    
    71.    
    72.    
    73.    
    74.    
    75. }
    76.  
    77.  
    78.  
    79.