전체 글 134

[C#] Action Invoke로 인자 전달하기

public class Class1 : MonoBehaviour { Action action; private void Trigger() { action.Invoke(); } } public class Class2 : MonoBehaviour { private void Start() { action += {Class1 Component}.ActionFunc } public void ActionFunc() { Debug.Log("action"); } } 기본적으로 Action을 사용해서 다른 클래스의 특정 함수를 동작시키기 위해서는 1. Action 변수 생성 2. 다른 클래스에서 해당 Action에 함수를 추가 3. Action을 Invoke 하면 다른 클래스의 해당 함수가 실행 하는 식으로 동작한다 그런..

[Error] get_persistentDataPath is not allowed to be called from a MonoBehaviour constructor

GameManagerEx 스크립트 파일에서 로컬 저장 기능 구현을 위해 path 변수를 선언하는 과정에서 에러 메시지가 발생하였다 public string _path = Application.persistentDataPath + "/SaveData.json"; UnityException: get_persistentDataPath is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'Managers' on game object '@Managers'. See "Script Seriali..

[Unity] Rect Transform Animation Position 변경하기

Rect Transform을 갖고 있는 텍스트 오브젝트에 애니메이션을 붙이려고 했는데, Position Property를 선택했더니 Z 포지션밖에 변경할 수가 없었다 Position 대신 Anchored Position을 사용해야 x와 y의 위치를 조정할 수 있다 Anchored가 붙어 있어 Anchors를 조정하는 프로퍼티라고 생각했는데, Anchors 프로퍼티는 따로 있었다 출처: https://forum.unity.com/threads/i-can-only-change-rect-transforms-z-position.328178/

[Unity] AddListener로 이벤트 추가하기

기본적으로 유니티 인스펙터 창에서 위와 같은 창에서 이벤트를 연결할 수 있으나, 좀 더 편하게 스크립트 상에서 연결을 해 볼 것이다 Button 컴포넌트의 OnClick 뿐만 아니라 Slider의 OnValueChanged 등에도 같은 방식으로 연결이 가능하다 public class ClickExample : MonoBehaviour { public Button yourButton; void Start() { Button btn = yourButton.GetComponent(); btn.onClick.AddListener(TaskOnClick); } void TaskOnClick() { Debug.Log("You have clicked the button!"); } } 유니티 공식 문서 상의 예제이다 B..

[C#] const, readonly, static

static 여러 객체가 같은 값을 공유해야 할 때 사용한다 public class Counting() { public static int staticCount = 0; public int count = 0; public Counting() { staticCount++; count++; } } 위와 같이 클래스를 선언한 다음, 아래와 같이 다른 클래스에서 해당 클래스로 인스턴스를 생성한다면 public class Scene() { private void Start() { Counting count1 = new Counting(); Counting count2 = new Counting(); Counting count3 = new Counting(); int count = Counting.staticCou..

[Unity] Text Mesh Pro에서 한글 폰트가 깨지는 현상

전체가 다 깨지기도 하고 일부만 깨지기도 하는 문제가 발생했는데 폰트 에셋 파일의 인스펙터 창에서 Atlas Population Mode를 Dynamic으로 변경하니 해결되었다 아래 Sampling Point Size도 폰트에 맞게끔 조정하면 된다는데 우선 기본값으로 놔두어도 문제 없었다 참고: https://blockdmask.tistory.com/590 +) 이후로 또 폰트가 깨지는 문제가 발생하여 추가로 찾아보니 Atlas Width와 Atlas Height 값을 조정해 주니 해결되었다 해상도를 높게 설정할 수록 품질이 높아지나, 동시에 메모리도 그만큼 추가로 잡아 먹으니 고려해서 설정할 것 (* 여기서 Atlas란 컴퓨터 그래픽스에서 사용하는 용어로써, 여러 이미지 또는 텍스처를 하나의 큰 이미지..

[Unity] Text 길이에 맞게 배경 이미지 조절하기

위처럼 경고 메시지를 출력할 때 텍스트 길이에 맞게끔 뒤에 배경 이미지가 조절되게 만드는 방법 이런 식으로 이미지 컴포넌트 산하에 Text를 넣어준다 그리고 이미지 컴포넌트(Panel)에 이 두 가지 컴포넌트를 추가해준다 나의 경우 안에 들어갈 요소가 텍스트 하나라서 Horizontal 레이아웃이나 Vertical 레이아웃이나 상관 없으나 만약 여러 요소가 들어간다면 그에 맞게끔 레이아웃 그룹을 선택해 주면 된다 우선 Layout Group 컴포넌트에서 Control Child Size의 Width와 Height를 체크해준다 * Child(=Text)가 늘어남에 따라 Text 오브젝트의 길이를 조절해주기 위함 만약 텍스트가 늘어남에 따라 그냥 가로로만 늘어나게 하고 싶으면 Width에만 체크해 줘도 무방..

[C#] Action 이벤트가 중복 실행되는 문제

가끔 Action 이벤트가 중복으로 실행되는 문제가 발생하는데 그에 대한 해결법이다 1. 제거하고 추가하기 * -=를 사용해서 제거하게 되면, 존재하지 않더라도 오류가 발생하지 않는다 class.actionInvoke -= actionEvent; class.actionInvoke += actionEvent; 2. 단일 이벤트만 연결한다면 단순 대입 연산자를 사용하기 class.actionInvoke = actionEvent; 하나의 action에 하나의 이벤트만 연결한다면 해당 이벤트 하나만 연결되게 된다

[Unity] 오브젝트 위치를 Tilemap/GridLayout 칸에 맞추기

World나 Screen 좌표계 외에도 Tilemap이나 GridLayout을 기준으로 오브젝트들의 위치를 조절할 수 있다 GridLayout // Snap the GameObject to parent GridLayout using UnityEngine; public class ExampleClass : MonoBehaviour { void Start() { GridLayout gridLayout = transform.parent.GetComponentInParent(); Vector3Int cellPosition = gridLayout.WorldToCell(transform.position); transform.position = gridLayout.CellToWorld(cellPosition); } ..