Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by L2GX · Aug 19, 2016 at 03:01 PM · variableslistsforeach

How to get variable from a 2D list in c#?

Hi, I've adapted the example list to the following class:

 using UnityEngine;
 using System.Collections;
 public class Island : MonoBehaviour
 {
     public static int postnumber;
     public static string islandname;
     public static int islandtype;
     public static int islandregion;
     public Island(int newPostNumber, string newName, int newIslandType, int newIslandRegion)
     {
         postnumber = newPostNumber;
         islandname = newName;
         islandtype = newIslandType;
         islandregion = newIslandRegion;
     } 
 }

and then in another script:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class SeedTurner : MonoBehaviour
 {
     public GameObject prefabisland;
     public GameObject[] islandprefablist;
     string localnewname;
 
     void Start()
     {
         //This is how you create a list. Notice how the type
         //is specified in the angle brackets (< >).
         List<Island> listedisland = new List<Island>();
         listedisland.Add(new Island(1, "Lisboa    ", 1, 1));
         listedisland.Add(new Island(2, "Alfama", 2, 1));
         listedisland.Add(new Island(3, "Torre de Belem    ", 23, 1));
 //list goes on...
 listedisland.Add(new Island(122, "Ameijeira", 13, 1));
                 listedisland.Add(new Island(123, "Lagos", 2, 1));
 
             Playercounter.postnumbercount = Playercounter.postnumbercount++;
 //playercounter is another script
             }


How do I get the string islandname from Island where the postnumber is Playercounter.postnumbercount? And the int islandtype?

I've looked all over the net, but I can't get the foreach to work.

All I'd need is an example based on the tutorial list, but every foreach I see is based on short arrays set up very differently, with numbered rows and columns and autogenerated content.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Landern · Aug 19, 2016 at 03:37 PM

Include both foreach and for loop examples:

 using UnityEngine;
  using System.Collections;
  using System.Collections.Generic;
  
  public class SeedTurner : MonoBehaviour
  {
     public GameObject prefabisland;
     public GameObject[] islandprefablist;
     string localnewname;
  
     void Start()
     {
         //This is how you create a list. Notice how the type
         //is specified in the angle brackets (< >).
         List<Island> listedisland = new List<Island>();
         listedisland.Add(new Island(1, "Lisboa    ", 1, 1));
         listedisland.Add(new Island(2, "Alfama", 2, 1));
         listedisland.Add(new Island(3, "Torre de Belem    ", 23, 1));
  //list goes on...
         listedisland.Add(new Island(122, "Ameijeira", 13, 1));
         listedisland.Add(new Island(123, "Lagos", 2, 1));
  
         foreach(Island island in listedisland)
         {
             if (island.postnumber == Playercounter.postnumbercount)
             {
                 Debug.Log("Found Island for player post number: " + Playercounter.postnumbercount + ", IslandName: " + island.islandname);
             }
         }
         
         //for(int i = 0; i < listedisland.Count; i++)
         //{
         //    if (listedisland[i].postnumber == Playercounter.postnumbercount)
         //    {
         //        Debug.Log("Found Island for player post number: " + Playercounter.postnumbercount + ", IslandName: " + listedisland[i].islandname);
         //    }
         //    
         //}
  
         Playercounter.postnumbercount = Playercounter.postnumbercount++;
         //playercounter is another script
     }
 }
Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image L2GX · Aug 19, 2016 at 03:42 PM 0
Share

Thank you! I'll try that, but I have a follow-up question:

Why is in foreach(Island island in listedisland) the second island not capitalised? Did you mean listedisland which I used when creating the list? Or is that (in the foreach) where I declare a new variable 'island' that I then use?

avatar image Landern L2GX · Aug 19, 2016 at 03:49 PM 0
Share

Because for each iteration of the loop you're saying: Foreach type Island in the Collection/List listedisland assign the element/item reference into a variable called "island", it's a temporary variable for each item in the Collection/List, once it hits the ending curly for the foreach loop it will take the next item in listedisland and push the reference into the variable "island". So again, it is just a variable for each iteration over the loop that can be used to reference the current item in the collection/list. In the for loop case it's access by index.

avatar image L2GX · Aug 19, 2016 at 04:05 PM 0
Share

All right, first of all the editor is only happy if i used capitalised Island.postnumber as below

 foreach (Island island in listedisland)
         {
             if (Island.postnumber == Playercounter.postnumbercount)
             {
                 Debug.Log("Found Island for player post number: " + Playercounter.postnumbercount + ", IslandName: " + Island.islandname);
             }
         }


then, for each line where I try to set a listedisland in the array, Unity tells me:

     You are trying to create a $$anonymous$$onoBehaviour using the 'new' keyword.  This is not allowed.  $$anonymous$$onoBehaviours can only be added using AddComponent().  Alternatively, your script can inherit from ScriptableObject or no base class at all
     UnityEngine.$$anonymous$$onoBehaviour:.ctor()
     Island:.ctor(Int32, String, Int32, Int32)
 SeedTurner:Start() (at Assets/_scripts/SeedTurner.cs:16)

Which I fixed by removing : $$anonymous$$onoBehaviour from my class definition script. This is now:

 using UnityEngine;
 using System.Collections;
 
 public class Island
 {

but it is not outputting anything in the log. I'll try and troubleshoot this more later tonight...

avatar image Landern L2GX · Aug 19, 2016 at 04:30 PM 1
Share

I'm so sorry, i didn't notice that you where using Static in your Island class. Since you marked each as static(the fields that can be set with a constructor) there will only be one reference to each of those fields(postnumber, islandname, etc) in the Island class. This is why when you reference the class member as apposed to the Instance member through the foreach(lower case "island") it was functioning, but the issue is these for fields in the Island class only exist once on teh Island class. You creating a List of it doesn't make any sense. The last created Island type will be the only accessible fields since each instance is overriding the previous. Do what i stated in my answer and restructure your Island class and remove the Static keyword.

 using UnityEngine;
  using System.Collections;
  public class Island : $$anonymous$$onoBehaviour
  {
      public int postnumber;
      public string islandname;
      public int islandtype;
      public int islandregion;
      public Island(int newPostNumber, string newName, int newIslandType, int newIslandRegion)
      {
          postnumber = newPostNumber;
          islandname = newName;
          islandtype = newIslandType;
          islandregion = newIslandRegion;
      } 
  }

tl;dr: Static members are shared between all instance of a class, where as instance members exist on EACH instance of a type.

avatar image L2GX L2GX · Aug 19, 2016 at 05:29 PM 0
Share

That did the trick! I also had to set the class of the list to ICompare as in the example, but those were non-blocking warnings.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

64 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Find entry in list based on part of the variable 0 Answers

How to deal with a missing reference when an object referred each frame from an array is destroyed along the way? 2 Answers

Why does foreach stop during a list? (reads one value only) 0 Answers

Using foreach to remove and delete bullet in List - C# 3 Answers

How do I access variables from Scriptable Objects in an array? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges