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

Vector3 export to WriteAllText

Discussion in 'Scripting' started by bplc, Sep 17, 2022.

  1. bplc

    bplc

    Joined:
    Mar 10, 2022
    Posts:
    104
    Hello, I have a little problem, I'm trying to export a Vector3 variable.

    I use WriteAllText to rewrite it.
    So not in a conventional way!
    I need to hard-store it in an external file.




    My problem is that it is written in the format (-3.94, 3.31, -18.56).
    Like a print or console.log



    Is me I need it to be in the format (-3.94f, 3.31f, -18.56f), with the float format.

    To be able to reuse it.

    Unless you're using a complicated increment, isn't there a simpler way?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,719
    If you insist on suffixing floating points with
    f
    that's great, but now you need to write the part that reads them back in. That's just... obvious.

    Load/Save steps:

    https://forum.unity.com/threads/save-system-questions.930366/#post-6087384

    An excellent discussion of loading/saving in Unity3D by Xarbrough:

    https://forum.unity.com/threads/save-system.1232301/#post-7872586

    Loading/Saving ScriptableObjects by a proxy identifier such as name:

    https://forum.unity.com/threads/use...lds-in-editor-and-build.1327059/#post-8394573

    When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. The reason is they are hybrid C# and native engine objects, and when the JSON package calls
    new
    to make one, it cannot make the native engine portion of the object.

    Instead you must first create the MonoBehaviour using AddComponent<T>() on a GameObject instance, or use ScriptableObject.CreateInstance<T>() to make your SO, then use the appropriate JSON "populate object" call to fill in its public fields.

    If you want to use PlayerPrefs to save your game, it's always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:

    https://gist.github.com/kurtdekker/7db0500da01c3eb2a7ac8040198ce7f6

    Do not use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.

    https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
     
  3. bplc

    bplc

    Joined:
    Mar 10, 2022
    Posts:
    104
    Thank you for your documentation.

    There is a real interest behind my request.

    I need to extract a coordinate. Here in vector3.

    Then store them in a file with my own extension, which will be sent to another computer..

    During my tests, I created a c# script with another c# script.
    And I wanted to write the value of my vector3 hard. The problem is those you know.
    I can very well retrieve each of my values independently and integrate my F manually.

    My question is :
    Is there another way to achieve this result?
     
  4. bplc

    bplc

    Joined:
    Mar 10, 2022
    Posts:
    104
    But of course as usual it's very simple...

    If I do a
    Vector3.ToString() 
    I have this format: (-3.94, 3.31, -18.56) The dot but not the F.


    And if I do a :
    Vector3.x.ToString()

    to add an F manually I have this format :

    -3,94 without the dot but a comma...

    Why make it simple when you can make it complicated..
     
  5. willemsenzo

    willemsenzo

    Joined:
    Nov 15, 2012
    Posts:
    585
    Instead of writing 3 lines of code to create a function that gives the output you want, you come here and write entire paragraphs. Talking about making things complicated.
     
  6. bplc

    bplc

    Joined:
    Mar 10, 2022
    Posts:
    104
    It's not wrong xD
    This is due to the fact that I am frustrated at not succeeding.

    yes I can do a float parse but it pissed me off, I like logical things and it doesn't make sense to me.
    Microsoft annoys me they do a great job but you always have little illogical details.
     
  7. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    331
    What is the illogical thing Microsoft did? you're talking about Vector3.x.ToString() returning -3,94 instead of -3.94?

    Well that's not illogical at all.

    float (or any number) .ToString() returns the number... in local culture. So I guess that your current PC local culture uses comma as a decimal separator. If you want to have a dot instead, you need to specify that either you do not want to use your local culture for formatting (InvariantCulture) or use a culture that does that (en-US for eg):

    Code (CSharp):
    1. Vector3.x.ToString(); // this will return -3,94 for you, or for users in France, Germany, Italy, Middle East...
    2. Vector3.x.ToString(CultureInfo.InvariantCulture); // this will always return -3.94 no matter the device culture/language.
    Now you may ask, why
    Vector3.ToString()
    uses "." and not my current culture spearator "," like
    float.ToString()
    ?

    Well
    Vector3
    is not a Microsoft type, it's a Unity one. Unity decided to always use "." as decimal separator, which makes sense since unlike numbers, vectors are generally not meant to be displayed to the end user at all, thus they do not need formatting.

    You too, just like what Unity did with Vector3, can customize the ToString() output of any class/struct you create, by just overriding the
    ToString()
    method:


    Code (CSharp):
    1. public class Enemy : MonoBehavior
    2. {
    3.     public string enemyName;
    4.     public float remainingHealth;
    5.  
    6.     public override string ToString()
    7.     {
    8.         return $"Enemy {enemyName}: Position {transform.position}, Health {remainingHealth}";
    9.     }
    10. }
    11.  
    12. Debug.Log(enemy.ToString());
    13. // writes: "Enemy Big Boss: Position (3, 4, 8) Health 0.7" instead of the default "Enemy" (class name)
    That's all.
     
    Last edited: Sep 18, 2022
    bplc likes this.
  8. pantang

    pantang

    Joined:
    Sep 1, 2016
    Posts:
    219
    This should export them to CSV, might want to add a few checks though...

    Code (CSharp):
    1. using UnityEngine;
    2. using System.IO;
    3.  
    4. public static class SaveLoadVectors
    5. {
    6.     public static void SaveVectors(string path, Vector3[] vectors)
    7.     {
    8.         string[] saveData = new string[vectors.Length];
    9.  
    10.         //Create csv strings for each vector
    11.         for (int i = 0; i < vectors.Length; i++)
    12.         {
    13.             saveData[i] = vectors[i].x.ToString() + "," + vectors[i].y.ToString() + "," + vectors[i].z.ToString();
    14.         }
    15.         //save the data
    16.         File.WriteAllLines(path, saveData);
    17.     }
    18.  
    19.     public static Vector3[] LoadVectors(string path)
    20.     {
    21.         //load the file and create the array to populate
    22.         string[] loadData = File.ReadAllLines(path);
    23.         Vector3[] theseVectors = new Vector3[loadData.Length];
    24.  
    25.         //split the data and parse the floats
    26.         for(int i = 0; i < loadData.Length; i++)
    27.         {
    28.             string[] splitData = loadData[i].Split(',');
    29.             theseVectors[i] = new Vector3 { x = float.Parse(splitData[0]), y = float.Parse(splitData[1]), z = float.Parse(splitData[2]) };
    30.         }
    31.  
    32.         return theseVectors;
    33.     }
    34. }
     
  9. bplc

    bplc

    Joined:
    Mar 10, 2022
    Posts:
    104
    Nad_B you're a genius, you're right I got carried away for nothing, lack of sleep :/

    Thank you for your explanation it helped me a lot :)

    Indeed the local culture of my PC uses a comma as decimal separator.

    Thank you also pantang, your script is interesting.
     
    pantang and Nad_B like this.