2022년 9월 21일 수요일

unity screen space to world space

 


screen space 에 있는 ui를 월드 오브젝트 (target), 쪽에 움직이고 싶을때

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

using UnityEngine.UI;

public class ScreenSpaceToWorldPosition : MonoBehaviour
{

    public Transform Target;

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

    // Update is called once per frame
    void Update()
    {
        transform.position = Camera.main.WorldToScreenPoint(new Vector3(Target.position.x, Target.position.y, Camera.main.nearClipPlane));
    }

    IEnumerator thread_positionUpdate()
    {
       
    }

}

2022년 9월 20일 화요일

unity grid laout cell size ChangebyScripts

 



using UnityEngine;
using System.Collections.Generic;
 
namespace UnityEngine.UI
{
    [AddComponentMenu("Layout/Auto Expand Grid Layout Group", 152)]
    public class AutoExpandGridLayoutGroup : LayoutGroup
    {
        public enum Corner { UpperLeft = 0, UpperRight = 1, LowerLeft = 2, LowerRight = 3 }
        public enum Axis { Horizontal = 0, Vertical = 1 }
        public enum Constraint { Flexible = 0, FixedColumnCount = 1, FixedRowCount = 2 }
 
        [SerializeField]
        protected Corner m_StartCorner = Corner.UpperLeft;
        public Corner startCorner { get { return m_StartCorner; } set { SetProperty(ref m_StartCorner, value); } }
 
        [SerializeField]
        protected Axis m_StartAxis = Axis.Horizontal;
        public Axis startAxis { get { return m_StartAxis; } set { SetProperty(ref m_StartAxis, value); } }
 
        [SerializeField]
        protected Vector2 m_CellSize = new Vector2(100, 100);
        public Vector2 cellSize { get { return m_CellSize; } set { SetProperty(ref m_CellSize, value); } }
 
        [SerializeField]
        protected Vector2 m_Spacing = Vector2.zero;
        public Vector2 spacing { get { return m_Spacing; } set { SetProperty(ref m_Spacing, value); } }
 
        [SerializeField]
        protected Constraint m_Constraint = Constraint.Flexible;
        public Constraint constraint { get { return m_Constraint; } set { SetProperty(ref m_Constraint, value); } }
 
        [SerializeField]
        protected int m_ConstraintCount = 2;
        public int constraintCount { get { return m_ConstraintCount; } set { SetProperty(ref m_ConstraintCount, Mathf.Max(1, value)); } }
 
        protected AutoExpandGridLayoutGroup()
        { }
 
#if UNITY_EDITOR
        protected override void OnValidate()
        {
            base.OnValidate();
            constraintCount = constraintCount;
        }
#endif
 
        public override void CalculateLayoutInputHorizontal()
        {
            base.CalculateLayoutInputHorizontal();
 
            int minColumns = 0;
            int preferredColumns = 0;
            if (m_Constraint == Constraint.FixedColumnCount)
            {
                minColumns = preferredColumns = m_ConstraintCount;
            }
            else if (m_Constraint == Constraint.FixedRowCount)
            {
                minColumns = preferredColumns = Mathf.CeilToInt(rectChildren.Count / (float)m_ConstraintCount - 0.001f);
            }
            else
            {
                minColumns = 1;
                preferredColumns = Mathf.CeilToInt(Mathf.Sqrt(rectChildren.Count));
            }
 
            SetLayoutInputForAxis(
                padding.horizontal + (cellSize.x + spacing.x) * minColumns - spacing.x,
                padding.horizontal + (cellSize.x + spacing.x) * preferredColumns - spacing.x,
                -1, 0);
        }
 
        public override void CalculateLayoutInputVertical()
        {
            int minRows = 0;
            if (m_Constraint == Constraint.FixedColumnCount)
            {
                minRows = Mathf.CeilToInt(rectChildren.Count / (float)m_ConstraintCount - 0.001f);
            }
            else if (m_Constraint == Constraint.FixedRowCount)
            {
                minRows = m_ConstraintCount;
            }
            else
            {
                float width = rectTransform.rect.size.x;
                int cellCountX = Mathf.Max(1, Mathf.FloorToInt((width - padding.horizontal + spacing.x + 0.001f) / (cellSize.x + spacing.x)));
                minRows = Mathf.CeilToInt(rectChildren.Count / (float)cellCountX);
            }
 
            float minSpace = padding.vertical + (cellSize.y + spacing.y) * minRows - spacing.y;
            SetLayoutInputForAxis(minSpace, minSpace, -1, 1);
        }
 
        public override void SetLayoutHorizontal()
        {
            SetCellsAlongAxis(0);
        }
 
        public override void SetLayoutVertical()
        {
            SetCellsAlongAxis(1);
        }
 
        private void SetCellsAlongAxis(int axis)
        {
            // Normally a Layout Controller should only set horizontal values when invoked for the horizontal axis
            // and only vertical values when invoked for the vertical axis.
            // However, in this case we set both the horizontal and vertical position when invoked for the vertical axis.
            // Since we only set the horizontal position and not the size, it shouldn't affect children's layout,
            // and thus shouldn't break the rule that all horizontal layout must be calculated before all vertical layout.
 
            if (axis == 0)
            {
                // Only set the sizes when invoked for horizontal axis, not the positions.
                for (int i = 0; i < rectChildren.Count; i++)
                {
                    RectTransform rect = rectChildren[i];
 
                    m_Tracker.Add(this, rect,
                        DrivenTransformProperties.Anchors |
                        DrivenTransformProperties.AnchoredPosition |
                        DrivenTransformProperties.SizeDelta);
 
                    rect.anchorMin = Vector2.up;
                    rect.anchorMax = Vector2.up;
                    rect.sizeDelta = cellSize;
                }
                return;
            }
 
            float width = rectTransform.rect.size.x;
            float height = rectTransform.rect.size.y;
 
            int cellCountX = 1;
            int cellCountY = 1;
            if (m_Constraint == Constraint.FixedColumnCount)
            {
                cellCountX = m_ConstraintCount;
                cellCountY = Mathf.CeilToInt(rectChildren.Count / (float)cellCountX - 0.001f);
            }
            else if (m_Constraint == Constraint.FixedRowCount)
            {
                cellCountY = m_ConstraintCount;
                cellCountX = Mathf.CeilToInt(rectChildren.Count / (float)cellCountY - 0.001f);
            }
            else
            {
                if (cellSize.x + spacing.x <= 0)
                    cellCountX = int.MaxValue;
                else
                    cellCountX = Mathf.Max(1, Mathf.FloorToInt((width - padding.horizontal + spacing.x + 0.001f) / (cellSize.x + spacing.x)));
 
                if (cellSize.y + spacing.y <= 0)
                    cellCountY = int.MaxValue;
                else
                    cellCountY = Mathf.Max(1, Mathf.FloorToInt((height - padding.vertical + spacing.y + 0.001f) / (cellSize.y + spacing.y)));
            }
 
            int cornerX = (int)startCorner % 2;
            int cornerY = (int)startCorner / 2;
 
            int cellsPerMainAxis, actualCellCountX, actualCellCountY;
            if (startAxis == Axis.Horizontal)
            {
                cellsPerMainAxis = cellCountX;
                actualCellCountX = Mathf.Clamp(cellCountX, 1, rectChildren.Count);
                actualCellCountY = Mathf.Clamp(cellCountY, 1, Mathf.CeilToInt(rectChildren.Count / (float)cellsPerMainAxis));
            }
            else
            {
                cellsPerMainAxis = cellCountY;
                actualCellCountY = Mathf.Clamp(cellCountY, 1, rectChildren.Count);
                actualCellCountX = Mathf.Clamp(cellCountX, 1, Mathf.CeilToInt(rectChildren.Count / (float)cellsPerMainAxis));
            }
 
            Vector2 requiredSpace = new Vector2(
                    actualCellCountX * cellSize.x + (actualCellCountX - 1) * spacing.x,
                    actualCellCountY * cellSize.y + (actualCellCountY - 1) * spacing.y
                    );
            Vector2 startOffset = new Vector2(
                    GetStartOffset(0, requiredSpace.x),
                    GetStartOffset(1, requiredSpace.y)
                    );
 
            for (int i = 0; i < rectChildren.Count; i++)
            {
                int positionX;
                int positionY;
                if (startAxis == Axis.Horizontal)
                {
                    positionX = i % cellsPerMainAxis;
                    positionY = i / cellsPerMainAxis;
                }
                else
                {
                    positionX = i / cellsPerMainAxis;
                    positionY = i % cellsPerMainAxis;
                }
 
                if (cornerX == 1)
                    positionX = actualCellCountX - 1 - positionX;
                if (cornerY == 1)
                    positionY = actualCellCountY - 1 - positionY;
 
                float realsize = ((width - (spacing[0] * (actualCellCountX - 1))) / actualCellCountX);
                SetChildAlongAxis(rectChildren[i], 0, startOffset.x + (realsize + spacing[0]) * positionX, realsize);
                SetChildAlongAxis(rectChildren[i], 1, startOffset.y + (cellSize[1] + spacing[1]) * positionY, cellSize[1]);
            }
        }
    }
}

2022년 9월 19일 월요일

unity world canvas button not working

 


월드 캔버스 버튼 클릭 안될때!!


Canvas GameObject에서 (WorldCanvas인 Canvas에서)


Graphic Raycaster

-> Ignore Reversed Graphics -> 혹시 체크 되있으면 체크 해제











2022년 9월 16일 금요일

[C#] XDocument, XmlDocument Convert, Revert

 






public static class DocumentExtensions
{
    public static XmlDocument ToXmlDocument(this XDocument xDocument)
    {
        var xmlDocument = new XmlDocument();
        using (var xmlReader = xDocument.CreateReader())
        {
            xmlDocument.Load(xmlReader);
        }
        return xmlDocument;
    }

    public static XDocument ToXDocument(this XmlDocument xmlDocument)
    {
        using (var nodeReader = new XmlNodeReader(xmlDocument))
        {
            nodeReader.MoveToContent();
            return XDocument.Load(nodeReader);
        }
    }
}

[Error] xml로드할 때 발생하는 에러 string to XML unity

 



//         string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
        if (LobbyMainScene_Xml.StartsWith(_byteOrderMarkUtf8))
        {
            LobbyMainScene_Xml = LobbyMainScene_Xml.Remove(0, _byteOrderMarkUtf8.Length);
        }
        xmlDoc.LoadXml(LobbyMainScene_Xml);





The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.







2022년 9월 14일 수요일

unity string ConvertTo enum

 


temp.cardGrades[0] = (CardGrade)Enum.Parse(typeof(CardGrade), convertData1[1]);


Unity SearchLogic 개선(List 처리 추가, 중복검색 클래스)

 



인자로 리스트 있을때 처리


///ProductName은 리스트 구조라서 람다식안에서 foreach를 한번 돌려줬다


이렇게 해서 해결


public List<CompanyInfo> SearhCompanyInf(int value, string input, bool sort= true)
    {
        Func<CompanyInfo, bool> condition;
        //Func<CompanyInfo, object> order;
        string search = input.ToLower();

        //if (value < 0 || value >= searchDropdown.options.Count)
        //    return new List<FixtureItemData>();
        switch (value) //Dropdown value에 따라 조건 설정
        {
            case 0: // 제조사
                condition = item => item.CompanyName.ToLower().Contains(search);
                //order = item => item.CompanyName;
                break;
            case 1: // 조명 이름

                ///ProductName은 리스트 구조라서 람다식안에서 foreach를 한번 돌려줬다
                condition = item =>
                {
                    foreach (var x in item.ProductNames)
                    {
                        if (x.Contains(search))
                            return true;
                    }
                    return false;
                };
                //order = item => item.ProductNames;
               
               


                //condition = item => item.FindCompany(search);
                //order = item => item.ProductNames;
                break;
            //case 2: // 채널
            //    condition = item => item.channelList.Count.ToString().Contains(search);
            //    order = item => item.channelList.Count;
            //    break;
            default: //모드
                condition = item => item.CompanyName.ToLower().Contains(search);
                //order = item => item.CompanyName;
                break;
        }

        int i = 1;
        IEnumerable<CompanyInfo> result;

        result = originTable.Where(condition);


        //result = sort ? result.OrderByDescending(order) : result.OrderBy(order);

        result = result.Select(x => new CompanyInfo
        {
            CompanyName = x.CompanyName,
            floorIdx = x.floorIdx,
            ProductNames = x.ProductNames
        });

        return result.ToList();

    }




///중복검색 제거 클래스
public class CompanyUiItem
{
    public string companyName;
    public string companyType;
    public string url;
    public List<string> products;
    public List<string> cars;


    public override bool Equals(object obj)
    {
        return this.companyName == ((CompanyUiItem)obj).companyName &&
            this.companyType == ((CompanyUiItem)obj).companyType &&
            this.cars.SequenceEqual(((CompanyUiItem)obj).cars)&&
            this.products.SequenceEqual(((CompanyUiItem)obj).products)
            ;
    }
    public override int GetHashCode()
    {
        return companyName.GetHashCode() ^ companyType.GetHashCode() ^ cars.GetHashCode()^products.GetHashCode();
    }

}


///다른방식의 검색

public List<CompanyUiItem> SearchTableData(string input)
    {
        if (input.Length == 0)
            return originTable;


        Func<CompanyUiItem,bool> condition_car; //검색 조건
        Func<CompanyUiItem, bool> condition_products; //검색 조건
        Func<CompanyUiItem, bool> condition_companyName; //검색 조건
        Func<CompanyUiItem, bool> condition_companyType; //검색 조건
       
        //Func<CompanyUiItem, object> order; //정렬 기준
        string search = input.ToLower(); //소문자로 변환

        condition_car = item => item.cars.Where(x=> x.ToLower().Contains(search)).Any();
        condition_products = item => item.products.Where(x => x.ToLower().Contains(search)).Any();
        condition_companyName = item => item.companyName.ToLower().Contains(search);
        condition_companyType = item => item.companyType.ToLower().Contains(search);






       
        IEnumerable<CompanyUiItem> result_car;
        IEnumerable<CompanyUiItem> result_products;
        IEnumerable<CompanyUiItem> result_company;
        IEnumerable<CompanyUiItem> result_type;

        result_car = originTable.Where(condition_car);
        result_products = originTable.Where(condition_products);
        result_company = originTable.Where(condition_companyName);
        result_type = originTable.Where(condition_companyType);

        //result = originTable.Where(condition_car).Where(condition_companyName).Where(condition_companyType).Where(condition_products);
        result_car = result_car.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });
        result_products = result_products.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });
        result_company = result_company.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });
        result_type = result_type.Select(x => new CompanyUiItem
        {
            companyName = x.companyName,
            companyType = x.companyType,
            cars = x.cars,
            products = x.products,
            url = x.url,
        });


       

       
        IEnumerable<CompanyUiItem> result  =
            new[] { result_car, result_products, result_company, result_type }.
            Where(x=>x!=null).
            SelectMany(x => x).
            Distinct();

       


        //Debug.Log($"car {result_car.Count()}");
        //Debug.Log($"products {result_products.Count()}");
        //Debug.Log($"result_company {result_company.Count()}");
        //Debug.Log($"result_type {result_type.Count()}");


        //Debug.Log($"result{result.Count()}");

        return result.ToList();
    }

git rejected error(feat. cherry-pick)

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