2023년 3월 30일 목요일

unity (waitUntil) 최적화 [unity coroutine optimization]

 



waitUntil을 추가했음



## 효과

yield new 로 생기는 가비지콜렉션을 줄일수있다.


참고

https://velog.io/@livelyjuseok/C-Unity-%EC%BD%94%EB%A3%A8%ED%8B%B4-Yield-%EC%B5%9C%EC%A0%81%ED%99%94-%ED%95%98%EA%B8%B0IEqualityComparer



## 사용예

```
yield return YieldCache.WaitForEndOfFrame;
        yield return YieldCache.WaitUntilcustom(() => isLoginSuccess);
        yield return YieldCache.WaitUntilcustom(() => FirebaseDataManager.Instance != null);
        yield return YieldCache.WaitUntilcustom(() => DataPersistenceManager.Instance != null);

        //yield return new WaitForEndOfFrame();
        //yield return new WaitUntil(() => isLoginSuccess);
        //yield return new WaitUntil(() => FirebaseDataManager.Instance !=null);
        //yield return new WaitUntil(() => DataPersistenceManager.Instance != null);

```




## 최적화 코드
```csharp 최적화 코드
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
static class YieldCache
{
    class FloatComparer : IEqualityComparer<float>
    {
        bool IEqualityComparer<float>.Equals(float x, float y)
        {
            return x == y;
        }
        int IEqualityComparer<float>.GetHashCode(float obj)
        {
            return obj.GetHashCode();
        }
    }


    class FloatComparerbool : IEqualityComparer<Func<bool>>
    {
        bool IEqualityComparer<Func<bool>>.Equals(Func<bool> x, Func<bool> y)
        {
            return x == y;
        }
        int IEqualityComparer<Func<bool>>.GetHashCode(Func<bool> obj)
        {
            return obj.GetHashCode();
        }
    }

    public static readonly WaitForEndOfFrame WaitForEndOfFrame = new WaitForEndOfFrame();
    public static readonly WaitForFixedUpdate WaitForFixedUpdate = new WaitForFixedUpdate();

    private static readonly Dictionary<float, WaitForSeconds> _timeInterval = new Dictionary<float, WaitForSeconds>(new FloatComparer());
    private static readonly Dictionary<float, WaitForSecondsRealtime> _timeIntervalReal = new Dictionary<float, WaitForSecondsRealtime>(new FloatComparer());
    private static readonly Dictionary<Func<bool>, WaitUntil> _waitUntill = new Dictionary<Func<bool>, WaitUntil>(new FloatComparerbool());

    public static WaitForSeconds WaitForSeconds(float seconds)
    {
        WaitForSeconds wfs;
        if (!_timeInterval.TryGetValue(seconds, out wfs))
            _timeInterval.Add(seconds, wfs = new WaitForSeconds(seconds));
        return wfs;
    }

    public static WaitForSecondsRealtime WaitForSecondsRealTime(float seconds)
    {
        WaitForSecondsRealtime wfsReal;
        if (!_timeIntervalReal.TryGetValue(seconds, out wfsReal))
            _timeIntervalReal.Add(seconds, wfsReal = new WaitForSecondsRealtime(seconds));
        return wfsReal;
    }

    public static WaitUntil WaitUntilcustom(Func<bool> state)
    {
        WaitUntil wfsReal;
        if (!_waitUntill.TryGetValue(state, out wfsReal))
            _waitUntill.Add(state, wfsReal = new WaitUntil(state));
        return wfsReal;
    }

}







2023년 2월 14일 화요일

2022년 11월 16일 수요일

실수로 git pull 햇을때 로컬 되살리기

 



>[!warning] # 무조건 지켜야 하는 법칙(로컬을 살리기위해,협업을 위해)

> git pull 을 하기전에 

> # **stash** 명령어로 로컬 저장!!

> - 반드시  를 해서 local의 변경사항을 저장하자!!!

> 

> 하지 않는다면 되돌릴수없는 강을 건너게 된다...



2022년 11월 2일 수요일

Unity UI On GameObjectPostion

 




void DrawTest()
    {

        // Offset position above object bbox (in world space)
        float offsetPosY = target.transform.position.y;

        // Final position of marker above GO in world space
        Vector3 offsetPos = new Vector3(target.transform.position.x, offsetPosY, target.transform.position.z);

        // Calculate *screen* position (note, not a canvas/recttransform position)
        Vector2 canvasPos;
        Vector2 screenPoint = Camera.main.WorldToScreenPoint(offsetPos);

        // Convert screen position to Canvas / RectTransform space <- leave camera null if Screen Space Overlay
        RectTransformUtility.ScreenPointToLocalPointInRectangle(MainCanvasRect, screenPoint, null, out canvasPos);

        // Set
        imageRectTransform.localPosition = canvasPos;
    }


DrawLine

 




  // Offset position above object bbox (in world space)
  float offsetPosY = target.transform.position.y + 1.5f;
 
  // Final position of marker above GO in world space
  Vector3 offsetPos = new Vector3(target.transform.position.x, offsetPosY, target.transform.position.z);
 
  // Calculate *screen* position (note, not a canvas/recttransform position)
  Vector2 canvasPos;
  Vector2 screenPoint = Camera.main.WorldToScreenPoint(offsetPos);
 
  // Convert screen position to Canvas / RectTransform space <- leave camera null if Screen Space Overlay
  RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPoint, null, out canvasPos);
 
  // Set
  markerRtra.localPosition = canvasPos;



2022년 10월 27일 목요일

ml agent unity 초기 설정방법(anaconda,Window)



1. Unity 설치 (2020.3이상)


  


2. anaconda 설치


  


3.가상환경 만들기


  

- conda create -n MLAgent python =3.7.9


  

  


4. 해당 가상환경에 pytorch설치


## pip3 install torch~=1.7.1 -f https://download.pytorch.org/whl/torch_stable.html


  





![[Pasted image 20221030163156.png]]




5. 해당 가상환경에 mlagent 설치


## python -m pip install mlagents==0.28.0


![[Pasted image 20221030163252.png]]


2022년 10월 26일 수요일

unity 2d sprite animation

 


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

[Serializable]
public struct SpriteInfo
{
    public Image sourceImage;
    public Sprite[] textureArray;
    public float frameRate;
   
}

public class SpriteAnimation : MonoBehaviour
{

    [SerializeField] SpriteInfo s_Info;


    [SerializeField] float frameTimer;
    [SerializeField] int currentFrame;
    [SerializeField] int frameCount;



    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("1"))
        {
            StartCoroutine(StartSprite(s_Info));
        }
    }



    IEnumerator StartSprite(SpriteInfo info)
    {
        frameTimer = info.frameRate;
        frameCount = info.textureArray.Length;

        //Rect rect = new Rect(0, 0, info.textureArray[0].width, info.textureArray[0].height);

        while (true)
        {
            frameTimer -= Time.deltaTime;
            if (frameTimer <= 0f)
            {
                frameTimer += info.frameRate;
                currentFrame = (currentFrame + 1) % frameCount;
                info.sourceImage.sprite = info.textureArray[currentFrame];
                Debug.Log(info.sourceImage.sprite.name);
                //info.sourceImage.sprite = Sprite.Create(info.textureArray[currentFrame],rect,Vector2.zero);
            }
            yield return new WaitForEndOfFrame();
        }
    }


}






git rejected error(feat. cherry-pick)

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