Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
0
Question by pvzkiller · Oct 22, 2012 at 07:03 AM · 2darraytextfiledimensional

2D array problem in C#

Hi,

In my external file, I have this unique and short line:

001///526.9785///918.133///001///1484.1///397.38///

You can read it like this:

type1///x coordinate of type0///y coordinate of type0///type2///x coordinate of type1///y coordinate of type1

I successfully get Unity to read the file and return this a single string variable; this is not a problem in any way. However, I must split this retrieved string to smaller chunks so that I can store the string values seperately in variables, just like this:

string xoffirstobject = x coordinate of type0;

string yoffirstobject = y coordinate of type0;

string xofsecondobject = x coordinate of type1;

string yofsecondobject = y coordinate of type1;

I am new to multi-dimensional arrays, and all answers that could help me understand are mainly coded in Javascript or too specific to somebody else's situation, and I am coding in C# only. I tried to understand the Javascript examples (did many tests to adapt their code) for 7 hours now but all I tried to find is a huge headache...

How to proceed? Here below I post my code. Don't take much attention to my actual syntax, I know it is not logic or returning a 2D array, but instead please tell me how to achieve this in the actual context.

Here it is (sorry I do not include variable declarations):

         if(GUI.Button(new Rect(90,10,70,30), "Load...")) 
         {
             //Retrieve the text from the external text file and store it in a string variable
             theSourceFile = new FileInfo ("C:/unityexport/test.txt");
             reader = theSourceFile.OpenText();
             text = reader.ReadLine();
             reader.Close();

             //I set u<3 because I have only 2 types currently in my external text file. But this is the part that is not working properly.
             for (int u=1;u<3;u++)
             {
             string[] dataLinestype = text.Split("///"[u]);
             string[] dataLinesx = text.Split("///"[0]);    
             string[] dataLinesy = text.Split("///"[0]);
                 
                Debug.Log("............................ type: " + dataLinestype[u] + " x: " + dataLinesx[0] + " y: " + dataLinesy[0]);
             }    
             
     
         }


NOTE that I am generating the text file myself, so I can put any seperating character at any desired position if this is a problem. I want the most simple-to-understand way. Please help me!

Comment
Add comment · Show 2
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 Fattie · Oct 22, 2012 at 07:13 AM 0
Share

use only List ... never arrays

unityGE$$anonymous$$S.com ...

avatar image Eric5h5 · Oct 22, 2012 at 07:32 AM 0
Share

No, there's no problem using arrays. Normally you use List if you need to add/subtract from the array, otherwise you're generally better off with fixed-size arrays.

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Tichau · Oct 22, 2012 at 09:08 AM

You can write your triplet like this : 001,526.9785,918.133;001,1484.1,397.38;

and split them with :

 string[] triplets = data.Split(';');
 for (int i = 0; i < triplets.Length; ++i)
 {
   string[] values = triplets[i].Split(',');
   if (values.Lenght != 3)
     continue;
 
   int type = int.Parse(values[0]);
   float xValue = float.Parse(values[1]);
   float yValue = float.Parse(values[2]);
 
   // Do what you want with values...
 }

Hope it help :)

Comment
Add comment · Show 1 · 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 pvzkiller · Oct 22, 2012 at 04:29 PM 0
Share

This is the most easy solution, and I got it to work without ANY problem (well in fact there is an error, this is Length and not Lenght ;) ). However I read carefully Robin's solution too and if I could accept 2 answers, I would have done without any doubt. Robin's solution is more flexible, in the sense where Tichau's solution implies that every type has always 2 values. I would have to make another for loop check for types having 0,1 or more than 2 values. But I can live with this, the solution is shorter and easier to understand, and Tichau's attributed variables, which is welcome since it helped me to understand faster.

avatar image
1

Answer by robhuhn · Oct 22, 2012 at 10:09 AM

The method Split splits a string into an Array on the basis of the given delimiter characters.

With that you don't need the first loop for (int u=1;u<3;u++) because you can split the whole content of your file. The second issue is that the parameter you are passing to the split method is "///"[u] or "///"[0]. Each string is nothing but a character array - here you take the array ['/', '/', '/'] and get the item at "u" or 0. What you might have thought of is this line `text.Split("///".ToCharArray(), u)` or similar but this would take each '/' as delimiter instead of the whole sequence "///".

I would recommend using two delimiters to reflect the structure of a 2D-Array and using regular expressions if you need to take a character sequence as delimiter.

 private List<string[]> data = new List<string[]>();
 
 private Regex itemRegex = new Regex("---");
 private Regex valueRegex = new Regex("///");
 
 // Use this for initialization
 void Start () 
 {
     //coming from extern
     string content = "001///526.9785///918.133---001///1484.1///397.38";
 
     //the items were split by "---" and stored in dataRoot
     string[] dataRoot = itemRegex.Split(content);
     
     foreach (string item in dataRoot) 
     {
         //each item were split here by "///". 
         //The result is an array with all values of that item.
         string[] itemValues = valueRegex.Split(item);
         
         //all values representing the item are added to a list. There could be 2 items or thousands.  
         data.Add(itemValues);
         
         //Debug:
         Debug.Log(string.Format("Item root ({0})", item));
         foreach (string v in itemValues) 
         {
             Debug.Log(string.Format("\t\t- value: {0}", v));
           }
         Debug.Log("\n");
         
         
     }
 }

Don't forget to use 'System.Text.RegularExpressions' for RegExp and 'System.Collections.Generic' for the List.

If you want it even easier you could create a Json-string and parse it right into your model class but thats another part.

Comment
Add comment · 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

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

12 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

Related Questions

How to read text file from resources and store into 2d array 3 Answers

How to access 2d array in outside script 1 Answer

How can I read data from a text file, putting a large amount of data into structures 2 Answers

How to FindChild RectTransform and access its Text 2 Answers

GUIText in 2D project is not rendering anywhere 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