티스토리 뷰

Unity

Unity_ Vector 3 _ CSV file

잉_민 2023. 6. 10. 19:39
728x90
반응형

간단 !

Unity용 매우 간단한 CSV 리더

https://bravenewmethod.com/2014/09/13/lightweight-csv-reader-for-unity/#comment-7111

 

Lightweight CSV reader for Unity

Managing game data in Unity scene objects can get really painful especially when more than one people needs to edit the same thing. It’s usually better to have some data in CSV file where it …

bravenewmethod.com

 

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
 
public class CSVReader
{
    static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
    static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
    static char[] TRIM_CHARS = { '\"' };
 
    public static List<Dictionary<string, object>> Read(string file)
    {
        var list = new List<Dictionary<string, object>>();
        TextAsset data = Resources.Load (file) as TextAsset;
 
        var lines = Regex.Split (data.text, LINE_SPLIT_RE);
 
        if(lines.Length <= 1) return list;
 
        var header = Regex.Split(lines[0], SPLIT_RE);
        for(var i=1; i < lines.Length; i++) {
 
            var values = Regex.Split(lines[i], SPLIT_RE);
            if(values.Length == 0 ||values[0] == "") continue;
 
            var entry = new Dictionary<string, object>();
            for(var j=0; j < header.Length && j < values.Length; j++ ) {
                string value = values[j];
                value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
                object finalvalue = value;
                int n;
                float f;
                if(int.TryParse(value, out n)) {
                    finalvalue = n;
                } else if (float.TryParse(value, out f)) {
                    finalvalue = f;
                }
                entry[header[j]] = finalvalue;
            }
            list.Add (entry);
        }
        return list;
    }
}

Drop this in your Scripts folder as CSVReader.cs and make folder Resources under your Assets folder. Put there any CSV files you want to use.

 

사용 예시

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class Main : MonoBehaviour {
 
    void Awake() {
 
        List<Dictionary<string,object>> data = CSVReader.Read ("example");
 
        for(var i=0; i < data.Count; i++) {
            print ("name " + data[i]["name"] + " " +
                   "age " + data[i]["age"] + " " +
                   "speed " + data[i]["speed"] + " " +
                   "desc " + data[i]["description"]);
        }
 
    }
 
    // Use this for initialization
    void Start () {
    }
 
    // Update is called once per frame
    void Update () {
 
    }
}

https://github.com/tikonen/blog/tree/master/csvreader

 

GitHub - tikonen/blog: Blog snippets

Blog snippets. Contribute to tikonen/blog development by creating an account on GitHub.

github.com

CSV 데이터를 변환하기 위해 앱에서 사용된 훌륭한 코드입니다.
관심 있는 경우 사소한 수정 – 특히 인용된 섹션이 끝에 있는 경우(예: "Hello said \"Bob\"") 따옴표가 포함된 문자열을 처리하지 않는 것으로 나타났습니다. 트림은 끝에 있는 모든 따옴표를 제거합니다.
함수 추가:
public static string UnquoteString(string str)
{
if (String.IsNullOrEmpty(str))
return str;

정수 길이 = str.Length;
if (길이 > 1 && str[0] == '\”' && str[길이 – 1] == '\”')
str = str.Substring(1, 길이 – 2);

반환 str;
}
그런 다음 내부 루프를 다음과 같이 변경합니다.

for(var j=0; j < header.Length && j < values.Length; j++ )
{
string value = values[j].Replace("\"\"","\"");
value = UnquoteString(value );
값 = value.Replace("\\", "");
….

유효한 CSV 데이터(새 줄로 구분된 줄과 쉼표로 구분된 열)를 제공하는 한 모든 소스에서 Regex.Split으로 문자열을 전달할 수 있습니다. 예를 들어 "col1,col2\n1,2\n3,4\n"은 올바르게 구문 분석됩니다.

이 구문 분석기는 셀의 개행을 지원하지 않습니다. 일반적으로 대부분의 도구는 적어도 쉽게 처리할 수 없으므로 CSV 파일에서 개행을 피해야 합니다. 일반적인 해결 방법은 마크업을 사용하는 것입니다. 예를 들어 "This isline break"를 입력하고 구문 분석 후 마크업을 바꿉니다. 예: val.Replace("", "\n");

 

구분 문자를 셀 값으로 사용할 수 없습니다. ';'를 사용하려면 스플리터 조절기 표현식을 수정해야 합니다. 구분 기호에 대한 이스케이프 코딩을 지원하기 위한 열 구분 기호로.

';'에 대한 스플리터 정규 표현식 구분 기호는 간단한 변경입니다. 식에서: ";(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"

이스케이프 코딩을 위한 스플리터 정규식: “/(?<!\\),(?=(?:[^""]*""[^""]*"")*(?![^""]* ""))/". 이렇게 하면 코드 셀 값을 ','로 이스케이프 처리할 수 있습니다. 예를 들어 값 "10,11,12"는 "10\,11\,12"로 코딩됩니다.

 

내가 활용한 방법

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Main : MonoBehaviour
{
	public string IR_name; //file name
	//public GameObject sphere; // obj

	void Awake()
	{
		List<Dictionary<string, object>> data = CSVReader.Read(IR_name);

		List<float> timeSecList = new List<float>();
		List<Vector3> positionList = new List<Vector3>();
		List<float> azimuthList = new List<float>();
		List<float> elevationList = new List<float>();
		List<float> rList = new List<float>();

		for (var i = 0; i < data.Count; i++)
		{
			print("time(sec) " + data[i]["time(sec)"] + " " +
				   "Iall " + data[i]["Iall"] + " " +
				   "x " + data[i]["x"] + " " +
				   "y " + data[i]["y"] + " " +
				   "z " + data[i]["z"] + " " +
				   "azimuth " + data[i]["azimuth"] + " " +
				   "elevation " + data[i]["elevation"] + " " +
				   "r " + data[i]["r"]);
			float timeSec= float.Parse(data[i]["time(sec)"].ToString());
			timeSecList.Add(timeSec);
			float x = float.Parse(data[i]["x"].ToString());
			float y = float.Parse(data[i]["y"].ToString());
			float z = float.Parse(data[i]["z"].ToString());
			Vector3 position = new Vector3(x, y, z);
			positionList.Add(position);
			float azimuth = float.Parse(data[i]["azimuth"].ToString());
			azimuthList.Add(azimuth);
			float elevation = float.Parse(data[i]["elevation"].ToString());
			elevationList.Add(elevation);
			float r = float.Parse(data[i]["r"].ToString());
			rList.Add(r);

			//sphere 생성, position
			GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
			sphere.transform.position = new Vector3(x, y, z);

			//Calculate the azimuth and elevation angles in radians: 각도

			float azimuthRad = azimuth * Mathf.Deg2Rad;
			float elevationRad = elevation * Mathf.Deg2Rad;

			Vector3 direction = new Vector3(
			Mathf.Cos(elevationRad) * Mathf.Sin(azimuthRad),
			Mathf.Sin(elevationRad),
			Mathf.Cos(elevationRad) * Mathf.Cos(azimuthRad)
			);
			//sphere rotate
			sphere.transform.rotation = Quaternion.LookRotation(direction);
			//sphere scale
			float scale = r * 2f; // Multiply by 2 to get the diameter instead of the radius
sphere.transform.localScale = new Vector3(scale, scale, scale);

		}

	}

	// Use this for initialization
	void Start()
	{

	}

	// Update is called once per frame
	void Update()
	{


	}
}

시간순으로 생성하는것도해봐야지

728x90
반응형

'Unity' 카테고리의 다른 글

Unity_VR_oculus _UI _Click  (0) 2023.06.14
UNITY _ Keijiro_git _ Scoped Registries  (0) 2023.06.12
unity _ VR _oculus _ thumbstick _ joystick 회전  (0) 2023.06.07
Unity_Oculus_VR  (0) 2023.06.05
Unity_ postprocessing &fog  (0) 2023.01.16
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함
반응형