2019년 12월 29일 일요일

파일존재여부 확인

string _FIlestr = Application.dataPath+ "/playerInventory.json";
if (System.IO.File.Exists(_FIlestr))
{
//파일존재
}
else
{
//파일없음
}
string _FIlestr = Application.dataPath+ "/playerInventory";
주의 이런식으로 경로에서 확장자를 빼면 무조건 파일이 없다고 나온다

2019년 12월 26일 목요일

float를 스트림 byte array로 받을때 유의사항

byte[] = {0,0,63,128} = 1
byte[] = {128,63,0,0} = 쓰레기값
역순으로 데이터를 읽고있을수도 있다 주의!

[Unity] int또는 float를 byte 배열 타입으로 변환,byte배열을 int또는 float으로 변환

아래는 4개의 길이를 갖는 byte 배열을 int 로 바꾸거나 int 를 4개의 길이를 갖는 byte 배열로 바꾸는 것이다.
// 아래의 방법 외에 다음과 같이 간단한 방법도 존재한다.  :
//   byte[] byteArray = ByteBuffer.allocate(4).putInt(value).array();
public  byte[] intToByteArray(int value) {
  byte[] byteArray = new byte[4];
  byteArray[0] = (byte)(value >> 24);
  byteArray[1] = (byte)(value >> 16);
  byteArray[2] = (byte)(value >> 8);
  byteArray[3] = (byte)(value);
  return byteArray;
 }
 
public  int byteArrayToInt(byte bytes[]) {
 return ((((int)bytes[0] & 0xff) << 24) |
   (((int)bytes[1] & 0xff) << 16) |
   (((int)bytes[2] & 0xff) << 8) |
   (((int)bytes[3] & 0xff)));
} 
  이 코드는 자바 기준으로 작성되어 있어 big endian 방식으로 되어있는데, x86 계열에서 컴파일되는 C 에서는 little endian 방식으로 바꿔야한다.  예를들어 위 코드에서 배열 인덱스 순서만 0,1,2,3 에서 3,2,1,0 순으로 바꿔주기만 하면 된다. 아래와 같이 말이다. 
byteArray[3] = (byte)(value >> 24);
byteArray[2] = (byte)(value >> 16);
byteArray[1] = (byte)(value >> 8); 
byteArray[0] = (byte)(value); 


이제 위에 예제를 이용하여 Byte Array to Float, Float to Byte Array 로 변환하는 함수를 만들어 보겠
다.
public byte[] floatToByteArray(float value) {
 int floatValue =  Float.floatToIntBits(value);
 return intToByteArray(floatValue);
}

public float byteArrayToFloat(byte bytes[]) {
 int value =  byteArrayToInt(bytes);
 return Float.intBitsToFloat(value);
}
역시 JAVA 가 여러모로 편하다.
C/C++ 에서는 float -> int 주소를 포인터 캐스팅 하는 방법으로 아주 쉽게 바꿀 수 있는데, 환경에 따라서 불가능할수도 있다.  그럴 경우에는 아주 조금 번거롭게 변경해야 한다. 이 부분에 대하여 다음에 다뤄보겠다.


출처: https://dev.re.kr/24 [Dev.re.kr]

2019년 12월 13일 금요일

C# 상속(Unity Gameobject 관련)

  1. 이런식으로 상속받은 자식이 있으면
  2.  
  3. public class Skill_ezreal_Q : Skill_Info
  4. {
  5.  
  6. }
  7. 상속받은 자식만 붙은 게임오브젝트(Skill_ezreal_Q)에서
  8. GetComponent.<Skill_Info>()가 가능함.
  9. Skill_info에 데이터 수정 등 여러가지 기능을 할수있음

2019년 12월 9일 월요일

암호화복호화(jsonVersion)



JsonVersion


using UnityEngine;
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;


using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;




[Serializable]
public class Data
{
    public Inner iNner;
    public Inner ind;   
}

[Serializable]
public class Inner
{
    public int level;
    public int hp;
}








public class Test : MonoBehaviour {

    
    // Use this for initialization
    void Start () {

        Data testData = new Data();
        
        //Inner inner = new Inner();
        //inner.level = 3;
        //inner.hp = 888;
        //testData.iNner = inner;

        //오브젝트 암호화 저장
        //obj_encrypt_Save(testData, Application.dataPath + "/En/","En_Json.txt");

        //암호화 저장된 데이터 오브젝트에 Deserialize!!
        //decrypt_load(testData, Application.dataPath + "/En/", "En_Json");

        //Debug.Log("testData" + testData.iNner.hp);
        //복호화가 잘 되었는지 파일로 내려서 확인
        //CreateJsonFile(Application.dataPath, "복호화확인" , ObjectToJson(testData));
    }


    //오브젝트를 암호화 하여 text로 저장
    public void obj_encrypt_Save(object obj,string filePath,string fileName)
    {
        string json = ObjectToJson(obj);
        string enc = DataEncryptDecrypt.encrystringData(json);
        CreateJsonFile(filePath, fileName, enc);
    }


    //text를 불러와 복호화 후 오브젝트에 Deserailize
    public void decrypt_load<T>(T obj, string En_filePath, string fileName)
    {
        FileStream filestream = new FileStream(string.Format("{0}/{1}.json", En_filePath, fileName), FileMode.Open);
        byte[] data = new byte[filestream.Length];
        filestream.Read(data, 0, data.Length);
        filestream.Close();
        string jsonData = Encoding.UTF8.GetString(data);
        string de_data = DataEncryptDecrypt.Decrypt(jsonData);
        JsonUtility.FromJsonOverwrite(de_data, obj);
    }

    




    string ObjectToJson(object obj)
    {
        return JsonUtility.ToJson(obj);
    }

    T JsonToObject<T>(string jsonData)
    {
        return JsonUtility.FromJson<T>(jsonData);
    }
    void CreateJsonFile(string createPath,string fileName,string jsonData)
    {
        FileStream fileStream = new FileStream(string.Format("{0}/{1}.json", createPath, fileName), FileMode.CreateNew);
        byte[] data = Encoding.UTF8.GetBytes(jsonData);
        fileStream.Write(data, 0, data.Length);
        fileStream.Close();
    }

    //T LoadJsonFile<T>(string loadPath, string fileName)
    //{
    //    FileStream filestream = new FileStream(string.Format("{0}/{1}.json", loadPath, fileName), FileMode.Open);
    //    byte[] data = new byte[filestream.Length];
    //    filestream.Read(data, 0, data.Length);
    //    filestream.Close();
    //    string jsonData = Encoding.UTF8.GetString(data);
    //    return JsonUtility.FromJson<T>(jsonData);
    //}
}

2019년 12월 8일 일요일

randomMove

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
using System.Collections;
 
using System.Collections.Generic;
 
using UnityEngine;
 
using UnityEngine.AI;
 
public class Move : MonoBehaviour
 
{
 
 
 
    private NavMeshAgent agent;
 
    public Transform target;
 
    public Vector3 RandomNavSpherePos;
 
 
 
    public float wanderRadius;
 
    //public float wanderTimer;
 
    //public float timer;
 
 
 
    public bool isResetPos;
 
    public bool isMoveToTarget;
 
    public bool isMoveRand;
 
 
 
    private float distanceToTarget;
 
    public float targetAttackRange;
 
    // Start is called before the first frame update
 
    void Start()
 
    {
 
        agent = GetComponent<NavMeshAgent>();
 
        StartCoroutine(MoveToTarget());
 
        StartCoroutine(MoveRandom());
 
    }
 
 
 
    // Update is called once per frame
 
    void Update()
 
    {
 
        //agent.SetDestination(target.position);
 
        if (Input.GetKeyDown("1"))
 
        {
 
            //가운데로 리턴
 
            agent.SetDestination(new Vector3(000));
 
        }
 
 
 
    }
 
 
 
    IEnumerator MoveToTarget()
 
    {
 
        while (true)
 
        {
 
            if (isMoveToTarget)
 
            {
 
                agent.SetDestination(target.position);
 
            }
 
            yield return new WaitForSeconds(0.35f);
 
            CalDistance();
 
        }
 
    }
 
 
 
    public void CalDistance()
 
    {
 
        distanceToTarget = Vector3.Distance(this.transform.position, target.position);
 
 
 
 
 
        if (distanceToTarget > targetAttackRange)
 
        {
 
            isMoveToTarget = true;
 
        }
 
        else
 
        {
 
            Debug.Log("타겟과 나의 거리:" + distanceToTarget);
 
            isMoveToTarget = false;
 
        }
 
    }
 
 
 
    IEnumerator MoveRandom()
 
    {
 
        while (true)
 
        {
 
           
 
            bool isAbleValue = true;
 
            float dis;
 
 
 
            while (isAbleValue && isMoveRand)
 
            {
 
                RandomNavSpherePos = RandomNavSphere(transform.position, wanderRadius, -1);
 
                dis = Vector3.Distance(target.position, RandomNavSpherePos);
 
 
 
                if (dis > targetAttackRange)
 
                {
 
                    isAbleValue = false;
 
                }
 
                else
 
                    isAbleValue = true;
 
            }
 
 
 
            yield return new WaitForSeconds(0.3f);
 
            agent.SetDestination(RandomNavSpherePos);
 
 
 
 
 
        }
 
 
 
    }
 
 
 
    Vector3 RandomNavSphere(Vector3 origin, float dist ,int layermask )
 
    {
 
        Vector3 randDirection = Random.insideUnitSphere * dist;
 
        randDirection += origin;
 
        NavMeshHit navHit;
 
        NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
 
        return navHit.position;
 
    }
 
}
 
 
cs

Wander Patrol(Unity)

  1. #pragma strict
  2. import UnityEngine;
  3. import System.Collections;
  4. import UnityEngine.AI;
  5.  
  6.  
  7. //Public Variables
  8. public var wanderRadius : float;
  9. public var wanderTimer : float;
  10.  
  11. //Private Variables
  12. private var target : Transform;
  13. private var agent : NavMeshAgent;
  14. private var timer : float;
  15.  
  16. function Start ()
  17. {  
  18.    agent = GetComponent(NavMeshAgent);
  19.    timer = wanderTimer;
  20. }
  21.  
  22. function Update()
  23. {
  24.    timer += Time.deltaTime;
  25.    
  26.    if(timer >= wanderTimer)
  27.    {
  28.        var newPos : Vector3 = RandomNavSphere(transform.position, wanderRadius, -1);
  29.        agent.SetDestination(newPos);
  30.        timer = 0;
  31.    }
  32. }
  33.  
  34. function RandomNavSphere(origin : Vector3, dist : float, layermask : int):Vector3
  35. {
  36.    var randDirection : Vector3 = Random.insideUnitSphere * dist;
  37.    
  38.    randDirection += origin;
  39.    
  40.    var navHit : NavMeshHit;
  41.    
  42.    NavMesh.SamplePosition(randDirection, navHit, dist, layermask);
  43.    
  44.    return navHit.position;
  45. }

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...