Skip to content

Instantly share code, notes, and snippets.

@rc1
Last active January 25, 2017 10:16
Show Gist options
  • Save rc1/66f135f93ce9a140a8ab8a3c997b9152 to your computer and use it in GitHub Desktop.
Save rc1/66f135f93ce9a140a8ab8a3c997b9152 to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
public class DataLoader : MonoBehaviour {
// Filename (make sure it is in a folder called "Resources" so Unity includes it in the build)
public string filename = "test.csv";
// The is a simple list of each number
private List<int> values = new List<int>();
// As soon as it is added to the scene, load the data
public void Awake () {
// Load our values and save them to this
values = LoadValuesFromCSV( filename );
}
public void Update () {
// Get the current frame number and loop around the number of frames we have
var frameNumber = (Time.frameCount - 1) % GetNumberOfCompleteFramesIn( values );
// Privnt out the value of the first element
Debug.Log( frameNumber + ": " + GetValueFrom( values, frameNumber, 0 ) );
}
// I've made this method static, be passed the file name and return the
// result so it's not tied to this class
public static List<int> LoadValuesFromCSV ( string filename ) {
// Load up string a s a TextAsset
TextAsset csvTxt = Resources.Load( filename ) as TextAsset;
string textWithoutWithSpaces = Regex.Replace( csvTxt.text, @"\s+", "" );
// Create a list of string
List<string> valueListAsString = new List<string>( textWithoutWithSpaces.Split( ',' ) );
// Convert the the
return valueListAsString
// Strip out empty values
.Where( valueAsString => valueAsString != "" )
.ToList()
// Convert this List<string> to List<int>
.ConvertAll<int>( valueAsString => {
int valueAsInt = -1;
try {
valueAsInt = int.Parse( valueAsString );
} catch ( Exception e ) {
Debug.LogError( "Couldn't convert: '" + valueAsString + "'" );
Debug.LogError( e );
}
return valueAsInt;
});
}
// Sees how many frames are in list of values
public static int GetNumberOfCompleteFramesIn ( List<int> values, int rowsPerFrame = 181 ) {
return values.Count / rowsPerFrame;
}
// Returns -1 if the value is out of range
public static int GetValueFrom ( List<int> values, int frame, int row, int rowsPerFrame = 181 ) {
// Frame count to low
if ( frame < 0 ) {
return -1;
}
// Get the position in the value array
int index = (frame * rowsPerFrame) + row;
// See if we are out of range
if ( index >= values.Count ) {
return -1;
}
return values[ index ];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment