반응형

using UnityEngine; 
using UnityEngine.EventSystems; 
using DG.Tweening;   

public class WheelHandler : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler { 	 	
    RectTransform ImgRectTransform;   	
    
    void Start () { 		
        ImgRectTransform = GameObject.Find("Canvas/Wheel/ImageR").GetComponent(); 	
    } 	 	
    
    public void OnPointerDown(PointerEventData e){ 		
        rotateImage(e.position); 	
    } 	 	
    
    public void OnPointerUp(PointerEventData e){ 		
        rotateImage(e.position); 	
    } 	 	
    
    public void OnDrag(PointerEventData e){ 		
        rotateImage(e.position); 	
    } 	 	
    
    protected void rotateImage( Vector2 value ){ 		
        float _x = value.x - Screen.width/2; 		
        float _y = value.y - Screen.height/2; 		
        float _R; 		 		
        if(_x > 0){ 			
            _R = (Mathf.Atan(_y/_x) * Mathf.Rad2Deg); 		
        }
        else
        { 			
            _R = (Mathf.Atan(_y/_x) * Mathf.Rad2Deg) + 180; 		
        } 		 		
        
        ImgRectTransform.DORotate(new Vector3(0f,0f,_R),0.1f,RotateMode.Fast); 		 	
    } 
} 

 

반응형
반응형

Unity로 안드로이드 앱을 개발하다보면 스크롤 안에 버튼이 들어갈 경우가 종종 있다.

PC에서 테스트 할 때는 마우스로 잘 눌리던 버튼이 스마트 폰에 넣어서 테스트 해보면 간혹 잘 눌리지 않는 경우가 있다. 이럴때 EventSystem 설정을 바꿔줘야하는데 다음과 같이 세팅 하면 적당하다.

 

private const float inchToCm = 2.54f; 	 
[SerializeField] private EventSystem eventSystem = null; 	 
[SerializeField] private float dragThresholdCM = 0.5f; //For drag Threshold 

private void SetDragThreshold() { 	
    if (eventSystem != null) 	{ 		
        eventSystem.pixelDragThreshold = (int)(dragThresholdCM * Screen.dpi / inchToCm); 	
    } 
}     

void Awake() { 	
    SetDragThreshold(); 
}

 

반응형
반응형

로컬저장을 하기 위해 찾아보다가 Asset Store에서 “Simple Save”라는 놈을 발견했다. 급할때 그냥 돈주고 사는게 정신건강에 좋다. 지금 테스트 중인데 나름 편리하게 잘 만들어진 것 같다. https://www.assetstore.unity3d.com/kr/#!/content/28799 내가 필요한 건 리스트 형태의 데이터를 저장해야하는데 여러가지 데이터 형태를 컴포넌트 형태로 저장해준다. 하지만 List는 지원되지 않고 ArrayList는 지원이 되더라는… 그래서 찾아보다 보니 hashtable과 arraylist를 사용해야겠다는 결론이 났다. 그럼 어떻게 변환하고 가져다 쓰는가…

//저장할때는 단순하게 요렇게 저장하고 
Hashtable ht = new Hashtable(); 
ht.Add("username", "bamsik"); 
ht.Add("point", 1); 
ht.Add("grak", 1); 
ht.Add("bbak", 2); 
ht.Add("date", 20151007); 
ht.Add("game", 1);   
_gameDataVO.Add(ht);   

//불러올때는 이렇게 불러오고 변환한다. 
string jsonstring = JsonMapper.ToJson(_gameDataVO); 
JsonData JD = JsonMapper.ToObject(jsonstring); 
반응형
반응형

리스트를 사용하다 보면 원하는 요소의 값대로 정렬하고자 할 때가 있다.
그럴 때 적당히 수정해서 사용하면된다.

void swap(int _i, int _j) 	{ 		
    ItemHandler tempItem =  MainList[_i]; 		
    MainList[_i] = MainList[_j]; 		
    MainList[_j] = tempItem; 	
}   	

IEnumerator sorting() 	{ 		
    yield return new WaitForSeconds (0.5f);  		
    // 승점 정렬 		
    for(int i = 0 ; i < MainList.Count; i++ ) { 			
        for(int j = i + 1 ; j < MainList.Count; j++) { 				
            if(MainList[i].Point < MainList[j].Point) { 					
                swap(i, j); 				
            } 				
            else if(MainList[i].Point == MainList[j].Point  				        
            && MainList[i].Gold < MainList[j].Gold) {	// 동률일 경우, gold,  					
                swap(i, j); 				
            } 				
            else if(MainList[i].Point == MainList[j].Point  				        
            && MainList[i].Gold == MainList[j].Gold  				        
            && MainList[i].Silver < MainList[j].Silver){ // 동률에 gold까지 같으면 silver. 					
                swap(i,j); 				
            } 				
            else if(MainList[i].Point == MainList[j].Point  				        
            && MainList[i].Gold == MainList[j].Gold  				        
            && MainList[i].Silver == MainList[j].Silver  				        
            && MainList[i].Bronze < MainList[j].Bronze){ // 동률에 gold, silver까지 같으면 bronze. 					
                swap(i,j); 				
            } 				
            else if(MainList[i].Point == MainList[j].Point  				        
            && MainList[i].Gold == MainList[j].Gold  				        
            && MainList[i].Silver == MainList[j].Silver  				        
            && MainList[i].Bronze == MainList[j].Bronze  				        
            && MainList[i].Garak < MainList[j].Garak){ // 동률에 gold, silver, bronze까지 같으면 garak. 					
                swap(i,j); 				
            } 				
            else if(MainList[i].Point == MainList[j].Point  				        
            && MainList[i].Gold == MainList[j].Gold  				        
            && MainList[i].Silver == MainList[j].Silver  				        
            && MainList[i].Bronze == MainList[j].Bronze  				        
            && MainList[i].Garak == MainList[j].Garak  				        
            && MainList[i].Bbak > MainList[j].Bbak){ // 동률에 gold, silver, bronze, garak까지 같으면 bbak. 					
                swap(i,j); 				
            } 			
        } 		
    }   		
    
    for(int t = 0 ; t < MainList.Count; t++ ) { 			
        MainList[t].gameObject.transform.SetSiblingIndex(t+1); 		
    }   	
}
반응형
반응형

unity3d 5 가 설치되어있다는 가정하에 다음과같이 진행한다.



1. https://code.visualstudio.com/Download 에서 다운받아 설치한다. (VS Code 설치)






2. http://www.mono-project.com 에서 다운받아 설치. (Mono Project 설치)




3. Unity3d Preferences메뉴를 클릭해서 External toos에서 External Script Editor를 설치한 VS Code로 선택한다.




4. Unity3d Assets메뉴를 클릭해서 Sync MonoDevelop Project를 눌러준다.




반응형

'tip' 카테고리의 다른 글

GLB 용량줄이기 (feat.Draco)  (0) 2023.03.23
티스토리 블로그에 SyntaxHighlighter 3.0 적용하기  (0) 2015.02.10
반응형
출처 : http://www.wolfpack.pe.kr/123?category=2
1. Threading 사용하기
using UnityEngine; 
using System; 
using System.Threading;  

//쓰레드를 쓰겠다고 선언.  
public class ThreadOne : MonoBehaviour {      
    void Start(){         
        Debug.Log("카운트 0부터 49까지 세기!");         
        ThreadStart th = new ThreadStart(work); //1.work메소드를 위임.         
        Thread t = new Thread(th); //2.쓰레드생성.         
        t.Start(); //3.시작         
        Debug.Log("끝!");     
    }      
    
    public static void work(){         
        for (int i = 0; i<50; i++){             
            Debug.Log("Conut : " + i);         
        }     
    } 
} 
2. Threading 중지하기

쓰레드를 중지하기 위한방법은 2가지가 있음. Abort() : 강제 종료이며 어디에서 끝날지 모름. Join() : 쓰레드가 다 실행 될 때 까지 기다렸다가 종료.

using UnityEngine; 
using System; 
using System.Threading;  

public class ThreadOne : MonoBehaviour {      
    void Start(){         
        Debug.Log("카운트 0부터 1만까지 세기!");         
        ThreadStart th = new ThreadStart(work);         
        Thread t = new Thread(th);         
        t.Start(); //시작         
        t.Abort(); //강제종료         
        Debug.Log("끝!");     
    }      
    
    public static void work(){         
        for (int i = 0; i<10000; i++){             
            Debug.Log("Conut : " + i);         
        }     
    } 
} 

위 코드를 실행 시켰을 때 다음과 같은 출력을 보여준다.

 

Abort()로 종료 시키면 '0'까지 세고 끝이 날 때도 있고 '8'까지 세고 끝날 때도 있다.

 

반면 Join()으로 종료 시키면 다음과 같이 9999까지 출력 후 종료한다.

 

 

3.Threading 쉬게 하기

using UnityEngine; 
using System; 
using System.Threading;  

public class ThreadOne : MonoBehaviour {      
    void Start(){         
        Debug.Log("Start");         
        ThreadStart th = new ThreadStart(work);         
        Thread t = new Thread(th);         
        t.Start(); //시작         
        Debug.Log("end!");     
    }      
    
    public static void work(){         
        Thread.Sleep (100);         
        Debug.Log ("Sleep");     
    } 
} 

다시 살리는 명령어는 Thread.Resume()으로 하면 된다.

 

타원의 안은 상태 값, 화살표는 메소드를 나타낸다.

 
 
4.Multi Threading
using UnityEngine; 
using System.Collections; 
using System; 
using System.Threading;  

public class MultiThread : MonoBehaviour {          
    class Work{         
        int a;          
        
        public Work(int a){             
            a = a;         
        }          
        
        public void runit(){                          
            for(int i=0; i<10; i++){                 
                Debug.Log("Thread " + a + " Running : " + i);                 
                Thread.Sleep(100);             
            }         
        }
    }               
    
    void Start(){         
        Debug.Log ("start");         
        Work wk1 = new Work (1);         
        Work wk2 = new Work (2);         
        ThreadStart td1 = new ThreadStart (wk1.runit);         
        ThreadStart td2 = new ThreadStart (wk2.runit);         
        Thread t1 = new Thread (td1);         
        Thread t2 = new Thread (td2);         
        t1.Start ();         
        t2.Start ();      
    } 
} 

1번과 2번이 동시에 실행된다.

둘 중에 우선순위를 정하고자 할 때는 ThreadPriority 를 사용한다.

 
t1.Priority = ThreadPriority.Lowest; //1번 쓰레드 우선 순위 최하 
t2.Priority = ThreadPriority.Highest; //2번 쓰레드 우선 순위 최고 

 

멀티로 작업을 하다 보면 공통 변수로 작업해야 할 때가 있다. 이때 여러개의 쓰레드가 1개의 값을 건드리다 보면 값이 예상과 다르게 나올 수 가 있는데 이럴 땐 "lock"으로 묶어주거나 "Monitor.Enter()”와 "Monitor.Exit()”로 잡아줄 수 있다.

public void runit(){      	
    lock (this) { //또는 Monitor.Enter()        	
        for(int i=0; i<10; i++){       	
            Debug.Log("Thread " + a + " Running : " + i);            	
            Thread.Sleep(100);      	
        } 
    }//또는 Monitor.Exit(10); 
}  

 

반응형
반응형

 GameObject NotiBtn = new GameObject (); 
 NotiBtn.transform.SetParent(GameObject.Find ("Guest1/Home/Notification/NotiMask").transform); 
 NotiBtn.name = "NotiBtn---"; 
 NotiBtn.AddComponent (); 
 NotiBtn.GetComponent ().anchorMin = new Vector2 (0f,1f); 
 NotiBtn.GetComponent ().anchorMax = new Vector2 (0f,1f); 
 NotiBtn.GetComponent ().pivot = new Vector2 (0f,1f); 
 NotiBtn.transform.localPosition = new Vector3 (0f,0f,0f); 
 NotiBtn.AddComponent (); 
반응형
반응형

Sublime Text 2 는 확실히 가볍고 괜찮은 툴인듯하다.

유니티를 접한지 얼마 되지 않았지만 유니티에서 기본으로 제공하는 MonoDevelop은 상당히 무겁고 기능도 뭔가 불편하다는 느낌이다. 한글지원도 되지 않아 한글 타이핑이 되지 않는 현상도 있다.

계속 써오다가 오늘 구글링한 내용을 정리해 본다.

 

http://www.sublimetext.com/2

 

먼저 서브라임을 설치한 후, 

패키지 컨트롤 플러그인을 설치해야하는데 설치하는방법은 다음과같다.

 

https://packagecontrol.io/installation#st2

 

위 주소로 접속해서,

 

 

표기되어있는 부분의 스크립을 복사한다.

 

 

다시 서브라임으로 돌아와서 위 사진에 보이는 Show Console을 열어

복사해온 스크립을 붙여넣기 한 후 실행 시킨다.

 

 

 

그런 후 tools/Command Palette를 열어서

Package Control: Install Package 선택,

 

 

다음과 같은 화면이나오는데 검색창에 unity라고 치면

 

 

리스트가 나오는데 모두 설치해 주면 된다.

 

그리고 나서 유니티에 기본에디터인 Mono Develop 대신 Sublime으로 바꿔주도록 한다.

Unity / Preference / External Tools 에 있다.

 

 

 

이렇게 해주면 기존에 모노디벨롭으로 연결되던 게 Sublime으로 연결되어 열리게 된다.

 

- 서브라임에서 유니티 프로젝트를 관리 및 빌드를 수행하는 방법
 
- 콘솔 뷰 에러 메시지 더블 클릭의 연동 및 키워드 레퍼런스 페이지 연동
 
- 코멘트 토글 단축키 설정 ( 5번 참고 )
 
 

 

반응형
반응형

출처 : http://blueray21.tistory.com/30

http://alexgorbatchev.com/SyntaxHighlighter/manual/configuration/

class="brush: js; ruler: true; first-line: 10; highlight: [2, 4, 6]"

class HellowJava {     
    public static void main(String[] args)     {         
        System.out.println("Hello, Java ! ");     
    } 
}

 

반응형

'tip' 카테고리의 다른 글

GLB 용량줄이기 (feat.Draco)  (0) 2023.03.23
Unity Visual Studio Code 연결 mac  (0) 2015.06.23
반응형

JsonData를 사용하기 위해서는 먼저 에셋폴더에 플러그인 폴더에 LitJson파일을 복사해 넣어줘야 한다.

 

 

아래와같이 해주면 사용할 수 있다.

using LitJson;      

//////////////////////////////////////
//// Resources.load 사용해서 불러올때. ////
//////////////////////////////////////

private JsonData JsonList;

IEnumerator Start () 
{
	TextAsset t = (TextAsset) Resources.Load("listData", typeof(TextAsset));
	JsonList = JsonMapper.ToObject( t ); // TextAsset사용시에는 .json 형태의 파일을 .txt확장명으로 바꿔줘야함.
	Debug.Log ("text data - " + t.text);

	yield return t;

	ProcessList(t.text);
}

private void ProcessList(string jsonString)
{
	JsonList = JsonMapper.ToObject(jsonString);
}

///////////////////////////
//// WWW 사용해서 불러올때. ////
///////////////////////////

//로컬파일 불러올때.
string url = "file:System OSX/Users/beom-seokjang/Documents/unity/24_MSC_Memento_prototype/Assets/Resources/listData.json";

//웹에 있는 파일 불러올때.
string url = "http://bamsiki.com/listData.json";

WWW www = new WWW(url);

//Load the data and yield (wait) till it's ready before we continue executing the rest of this method.

yield return www;    

if (www.error == null)
{
	//Sucessfully loaded the JSON string
	Debug.Log("Loaded following JSON string" + www.data);

	//Process books found in JSON file
	ProcessList(www.data);
}
else
{
	Debug.Log("ERROR: " + www.error);
}
반응형

+ Recent posts