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

Question cannot call twice in foreach loop

Discussion in 'Scripting' started by usernotauser, Jul 12, 2022.

  1. usernotauser

    usernotauser

    Joined:
    Nov 6, 2021
    Posts:
    12
    I have written a script to retrieve values from JSON file, accessed via API.
    The problem is in the second foreach loop: when I try to assign value to variable value, VS higlights item2 and throws error CS0103 (The name 'item2' does not exist in the current context).
    However, when I print the output using Debug.Log (commented line in the code) Unity console output is correct.

    I assume that item2 in this case cannot be called the second time in the foreach loop, but why? And how to assign the variable in this case?


    Code (CSharp):
    1.  
    2. private void processJsonData(string _url)
    3.     {
    4.         Root jsnData = JsonUtility.FromJson<Root>(_url);  
    5.        
    6.         foreach (Datum item in jsnData.data)
    7.         {
    8.            
    9.             List<Sensordatavalue> values_list = item.sensordatavalues;
    10.             foreach (Sensordatavalue item2 in item.sensordatavalues)
    11.                
    12.                
    13.                 //Debug.Log("sensor3: " + "\n" + "Sensor id: " + Mathf.Abs(item2.id) + "\n" + "Value type:" + item2.value_type + "\n" + "Value: " + item2.value);
    14.  
    15.                 value_type = item2.value_type;
    16.                 value = item2.value;
    17.         }
    18.     }
    19.  
    Thank you in advance
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    Line 15 above is the ONLY thing in your
    foreach
    started on line 10.

    Line 16 is unrelated to the line 10
    foreach
    . Just because it is indented means nothing.

    You need to break out some extra curly braces
    {
    and
    }
    ...
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    You forgot the brackets around your inner for loop.
     
    usernotauser and Kurt-Dekker like this.
  4. usernotauser

    usernotauser

    Joined:
    Nov 6, 2021
    Posts:
    12
    Thank you!
     
    Kurt-Dekker likes this.