Get it on Google Play


Wm뮤 :: 사소한 c# 테크닉

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
전자과 게임프로그래머 (퇴사함)
2022.3.22f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


2020. 7. 8. 15:11 Unity/C#

 

 

//인스펙터에 script표시
GUI.enabled = false;
{
    var script = MonoScript.FromMonoBehaviour((MonoBehaviour)target);
    EditorGUILayout.ObjectField("Script", script, typeof(MonoScript), false);
}
GUI.enabled = true;

중괄호를 if문이나 for문같은게 없더라도 구획을 나누는데 쓰면 좋다

이렇게 만들어두면 필요할때 함수로 묶기도 편하다

region따위보다 가독성이 훨씬 좋다

 

그리고 아래는 아웃풋이 있을경우 예시


//worldPosition 2 screenPosition
Vector2[] screenPositions;
Vector2 screenHandlePosition;
{
    screenPositions = System.Array.ConvertAll(worldPositions, wp => RectTransformUtility.WorldToScreenPoint(cam, wp));
    screenHandlePosition = RectTransformUtility.WorldToScreenPoint(cam, worldHandlePoint);
}

 

 

 

 

 

foreach (var reloadEndSound in reloadEndSounds)
{
    reloadEndSound.Play();
}

foreach는 무조건 var를 쓰자. 어차피 용도는 한정되어 있으니까

참조변수는 s만 빼서 쓰면 식별도 편하고 좋다

 

 

 

 

switch (humanBodyBones)
{
    case HumanBodyBones.LeftUpperLeg:
    case HumanBodyBones.RightUpperLeg:
    case HumanBodyBones.LeftLowerLeg:
    case HumanBodyBones.RightLowerLeg:
        partDamage = 0.7f;
        break;
    case HumanBodyBones.Spine:
    case HumanBodyBones.Chest:
    case HumanBodyBones.UpperChest:
    case HumanBodyBones.Hips:
        partDamage = 1f;
        break;
    case HumanBodyBones.Neck:
    case HumanBodyBones.Head:
        partDamage = 2f;
        break;
    case HumanBodyBones.LeftShoulder:
    case HumanBodyBones.RightShoulder:
    case HumanBodyBones.LeftUpperArm:
    case HumanBodyBones.RightUpperArm:
    case HumanBodyBones.LeftLowerArm:
    case HumanBodyBones.RightLowerArm:
        partDamage = 0.7f;
        break;
}

 

책이나 교수들이 스위치문 이상하게 알려주는데

조건마다 break 달 필요없다.

애초에 그럴거면 다중if 쓰지 뭐라러 스위치문을 쓰겠는가

 

 

 

public void PressButton(string enumName, int index)
{
    Debug.Log($"PressButton({enumName}, {index})");
    if (enumName == nameof(MainCategory))
    {
        mainCategory = (MainCategory)index;
    }
    if (enumName == nameof(CostumeCategory))
    {
        costumeCategory = (CostumeCategory)index;
    }
    if (enumName == nameof(AppearanceCategory))
    {
        appearanceCategory = (AppearanceCategory)index;
    }
}

else if 대신 다중if를 쓰자.

가끔 switch문이 제약조건으로 안 먹는 경우 다중if를 많이 쓴다

오잉? '처리량이 늘어나는데 왜 else if를 안 쓰지?' 하고 의아해 할것이다.

보통 이렇게 수동으로 분기처리하는 데이터는 양이 적기 때문에

처리량이 늘어나도 거의 영향을 안 주는데

else if는 맨 윗열이 삭제되거나 하면 일일히 else를 지워가면서 해야한다

몰론 엄청나게 무거운 로직을 처리할땐 else if를 써야겠지만 그럴일은 별로 없다

 

아래는 또다른 예시

public void Skill(int index)
{
    if (hp<=0)
    {
        return;
    }
    if (IsMine)
    {
        if (CurrentSkillDelay(index) > 0)
        {
            return;
        }
        for (int i = 0; i < 2; i++)
        {
            if (CurrentSkillTime(i) > 0)
            {
                return;
            }
        }
    }
    //스킬실행
}

만약 위 코드에 if else를 쓰고 작동부를 if블록 안쪽에 두었다면 엄청나게 복잡해졌을것이다

 

 

 

 

다중루프 탈출

변수둬서 if체크하며 탈출하지 말고

goto로 탈출하자

for (int i = 0; i < players.Length; i++)
{
    for (int j = 0; j < bullets.Length; j++)
    {
        if (CollisionCheck(players[i], bullets[j]))
        {
            goto LOOP_OUT;
        }
    }
}
LOOP_OUT:;

'Unity > C#' 카테고리의 다른 글

자주 쓰는 유니티 코드 모음  (0) 2020.07.09
스파인 관련함수  (0) 2020.07.02
Parent of RectTransform is being set with parent property  (0) 2020.06.29
posted by 모카쨩

저사양 유저용 블로그 진입