Search Unity

Updating gameobject position using data from a CSV fle

Discussion in 'Scripting' started by serhanguel, Aug 17, 2021.

  1. serhanguel

    serhanguel

    Joined:
    Jan 7, 2019
    Posts:
    7
    Hi. I have a gameobject (an animated 3D model) whose position I want to update at each frame by reading the corresponding position data from a CSV file. Data in the CSV file looks as follows:

    x,y,z
    -0.00609, -0.05716, 0.53728
    -0.01124, -0.04929, 0.53632
    -0.01307, -0.04817, 0.5361
    ...

    Is there a straightforward approach to read CSV input using C# ? My CSV file are not so big; they contain around 300 lines each, so I guess it would be easier to read everything into an array and then iterate inside the Update function. I will save each frame to an image after I do the position update but I already figured out how to do that part.

    Thanks.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    You can get CSV reader libraries but the main concern is compatibility with whatever Unity you're using, now and into the future. Some libraries are HORRIBLY over-engineered and require dot-net 2050 or whatever the latest C# is.

    Fortunately CSV is such a trivial format that it is probably easiest just to slice up the strings yourself, using either regular expressions or simple string search, splitting and slicing.

    https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-5.0

    https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=net-5.0

    Once you have chopped it all up into parts, parse the values with something like:

    https://docs.microsoft.com/en-us/dotnet/api/system.single.tryparse?view=net-5.0

    and use it however you like.
     
    serhanguel likes this.