[System.Flags]는 C#(.NET 프레임워크의 일부)에서 열거형(enum)을 플래그(flag)의 모음으로 처리해야 함을 나타내는 속성입니다. 이를 통해 비트 연산을 사용하여 enum 값을 결합할 수 있으며, 이는 코드에서 옵션 또는 상태 조합을 효율적으로 나타내는 데 도움이 됩니다.

[System.Flags]의 주요 사용 사례는 다양한 방식으로 결합될 수 있는 독립적인 옵션 또는 속성 집합이 있을 때입니다. 플래그 속성을 사용하면 단일 정수 값으로 이러한 옵션의 모든 조합을 나타낼 수 있습니다.

다음은 이 개념을 설명하는 예입니다:

[System.Flags]를 사용하지 않는 경우:

public enum Colors { Red, Green, Blue }

이 경우 변수에 한 번에 하나의 색상만 할당할 수 있습니다.

[System.Flags]를 사용하는 경우:

[System.Flags] public enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 }

이제 비트 OR 연산을 사용하여 색상을 결합할 수 있습니다:

Colors combinedColors = Colors.Red | Colors.Green;

combinedColors는 이제 Red와 Green 플래그를 모두 가지게 됩니다. 비트 AND 연산을 사용하여 특정 플래그가 설정되어 있는지 확인할 수도 있습니다:

bool isRedSet = (combinedColors & Colors.Red) == Colors.Red;

이를 통해 단일 정수 값으로 여러 옵션, 상태 또는 속성을 효율적으로 저장하고 조작할 수 있습니다. 그러나 플래그를 결합할 때 비트가 겹치지 않도록 열거 값으로 2의 거듭제곱(2^n)을 할당하는 것이 중요합니다.

블로그 이미지

RIsN

,

Mono를 계속 설치하라고 나오고, 설치해도  처리가 안될 때

  • C# Extension의 버전을 v1.25.0로 변경해볼 것
    • v1.25.1 ~ v1.25.4까지 문제 발생하는 경우 있음

블로그 이미지

RIsN

,

코드

  • enum 데이터
private enum CharacterVoice
{
    LJ8 = 15,
    POKI = 16,
    CHARASI = 65
}
  • 실행 코드
// :: enum 안의 모든 데이터를 가져옴
var values = System.Enum.GetValues(typeof(CharacterVoice));
// :: 데이터의 길이 만큼 랜덤 획득
int random = Random.Range(0, values.Length);
// :: 해당 enum의 수치값을 획득
Debug.Log((int)values.GetValue(random));

// >> 결과: 15 or 16 or 65

 

블로그 이미지

RIsN

,

백준 10869 : 사칙연산

C# 2020. 11. 14. 22:33

두 자연수 A와 B가 주어진다. 이때, A+B, A-B, A*B, A/B(몫), A%B(나머지)를 출력하는 프로그램을 작성하시오.

두 자연수 A와 B가 주어진다. (1 ≤ A, B ≤ 10,000)
첫째 줄에 A+B, 둘째 줄에 A-B, 셋째 줄에 A*B, 넷째 줄에 A/B, 다섯째 줄에 A%B를 출력한다.

:: 성공

: 개선점 : 없음

using System;

namespace Print05
{
    class Program
    {
        static void Main(string[] args)
        {
            // :: Input
            string[] input = Console.ReadLine().Split(' ');
            // :: Parsing
            int a = Int32.Parse(input[0]);
            int b = Int32.Parse(input[1]);
            // :: Result
            Console.WriteLine("{0}", a + b);
            Console.WriteLine("{0}", a - b);
            Console.WriteLine("{0}", a * b);
            Console.WriteLine("{0}", a / b);
            Console.WriteLine("{0}", a % b);
        }
    }
}

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

백준 2588 : 곱셈  (0) 2020.11.16
백준 10430 : 나머지  (0) 2020.11.15
백준 10998 : A×B  (0) 2020.11.13
백준 1008 : A/B  (0) 2020.11.12
백준 10172 : 개 // 성공  (0) 2020.11.07
블로그 이미지

RIsN

,

《文法》

【Nullじゃないなら実行】

// :: Callback
Callback_CompletedFX?.Invoke();
// :: Same the above
/*if (Callback_CompletedFX != null)
{
	Callback_CompletedFX();
}*/

《EASY to USE》

【EnumのDescriptionを取得して使用】

// :: Enums : Animation Key
private enum eAnimation
{
  [Description("idle@loop")]
  IDLE,
  [Description("run@loop")]
  RUN,
  [Description("walk@loop")]
  WALK
}

// :: for use enum Description
// ::: Ref : http://kawakawa2000.jugem.jp/?eid=27
// ::: I don't understand perfectly yet.
private string GetEnumDescription(eAnimation value)
{
	FieldInfo fi = value.GetType().GetField(value.ToString());
	var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

	var descriptionString = attributes.Select(ele => ele.Description).FirstOrDefault();

	if(descriptionString != null)
	{
		return descriptionString;
	}
	return value.ToString();
}

void Update() 
{
	anim.Play(this.GetEnumDescription(eAnimation.RUN));
}

【Unity Editorにツールを登録

// :: for Using
using UnityEditor;

// :: Easy to use
public class MenuTest : MonoBehaviour
{
    // :: Location
    [MenuItem("MyMenu/Delete All PlayerPrefs")]
    // :: Program : Delete All PlayerPrefs
    static void DeleteAllPlayerPrefs()
    {
        PlayerPrefs.DeleteAll();
        Debug.Log("deleted all player prefs");
    }
}

《イベント》

【ボタンにイベントリスナーを追加】

>>クリックすると動くように

// :: Add Event Listener
btn.onClick.AddListener(this.ClickedButton);

【数秒後に実行】
>>Singletonに定義してそれを持ってきて使うのも可能

<<CT_Ruler>>
// :: Do Action after Waiting
UIController.WaitForSecondsAndDo(10f, (() => { UIController.FadeIn(GOHolder.SPRITE_handRight); }));

<<Sing_UIController>>
// :: Do Action after Waiting
public void WaitForSecondsAndDo(float time, System.Action action)
{
	this.StartCoroutine(WaitForSecondsAndDoImplement(time, action));
}
private IEnumerator WaitForSecondsAndDoImplement(float time, System.Action action)
{
	yield return new WaitForSeconds(time);
	action();
}

【ゲーム停止】

// :: Pause Game
Time.timeScale = 0;
// :: RePlay Game
Time.timeScale = 1;

《出力》

【PrefabをベースにGameObjectの複製を作ってそれを画面に出力】

// :: Make GameObject & Render
GameObject prefab =  Resources.Load<GameObject>("ch_03_01");
GameObject clone =  Instantiate<GameObject>(prefab);

【出力する際に親(Parent)と位置を設定】

// :: Render Chest Closed and Set Position
// ::: Use Transform Parent
// ::: 1. GameObject
// ::: 2. Position
// ::: 3. Rotation
// ::: 4. Parent transform
chestClosed = Object.Instantiate<GameObject>(chestPrefabA, // 1
            lastTarget.transform.position + new Vector3(0, 0, 0.5f), // 2 
            Quaternion.Euler(-90, -90, 0), // 3
            lastTarget.transform); // 4

【出力してから親(Parent)を設定】

// :: Create Weapon and Set Parent
GameObject spear = Object.Instantiate<GameObject>(Resources.Load<GameObject>("Spear_7"));
spear.transform.SetParent(dummyRHand);
// :: Change Position
spear.transform.localPosition = new Vector3(0, 0, 0);
spear.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, 0));

【画面にいるGameObjectの出力を消す】

// :: Destroy Game Object
Destroy(itm);

【3Dのキャラ位置に合わせて2DキャンバスにHUDを出力】

// :: When Button Clicked : Show HUD
this.BUTTON_test.onClick.AddListener(() =>
{
	// :: Instantiate with Canvas
	var go = Instantiate<GameObject>(this.hudPrefab, this.canvas.transform);

	// :: Check Where do you want set the position
	// ::: Main Camera World Point => Screen Point
	var screenPoint = Camera.main.WorldToScreenPoint(playerGO.transform.position);

	// ::: Screen Point => Local(Canvas) Point
	Vector2 localPoint;
	// ::: ((RectTransform) Canvas Transform, Screen Point, Camera which you will set HUD, out local Point)
	RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)canvas.transform, screenPoint, this.uiCam, out localPoint);

	// :: Change HUD Local position
	go.transform.localPosition = localPoint;

	// :: Play and Destroy
	var hud = go.GetComponent<HUDText>();
	hud.Init(992);
	hud.Play();
	hud.Callback_Play = () => {
		Destroy(hud.gameObject);
	};
});

《方向と移動》

【1歩前に動く:マップ基準】

// :: Map Position
hero.transform.position += Vector3.forward;
//this.gameObject.transform.Translate(Vector3.forward, Space.Self);

1歩前に動く:自分基準】

// :: Self Position
hero.transform.position += hero.transform.forward;
//this.gameObject.transform.Translate(this.transform.forward, Space.World);

【目標の方向を見るように角度を修正】

// :: Look target Direction
Vector3 target = new Vector3(1, 0.49f, -2) - itm.transform.position;
itm.transform.rotation = Quaternion.LookRotation(target);

【目標を見てその方向に走る(結果:目標を通って走る)】

// :: Look at Target
this.transform.LookAt(target.transform);
// :: Move There with Translate
this.transform.Translate(this.transform.forward * 0.1f * Time.deltaTime, Space.World);

⇒まだ完全に理解していない。

【目標まで行く】

// :: Move Toward 
this.transform.position = Vector3.MoveTowards(this.transform.position, this.target.transform.position, 0.1f * Time.deltaTime);

《衝突》

【衝突無視】

// :: Find all BoxCollider2D
foreach (var itm in GameObject.FindObjectsOfType<BoxCollider2D>())
{
	// :: Player : Ignore it
	Physics2D.IgnoreCollision(playerRigidbody.gameObject.GetComponent<CircleCollider2D>(), itm, true);
}

【RayCastで衝突感知】

// :: Hit Checker
RaycastHit hit;
// :: When Racast Hit
// ::: (Start Position, Direction, Hit Object, Max Distance)
if (Physics.Raycast(this.player.transform.position, this.player.transform.forward, out hit, 1f))
{
	// :: Check Hit Object's Name
	Debug.Log(hit.transform.gameObject.name);
	// :: Show ray for Debug
	Debug.DrawRay(this.player.transform.position, this.player.transform.forward * 1f, Color.red);
}

《SCENE移動》

【SCENE移動時に完了をチェック、そしてその後に何かを実行】

// :: Load Scene with Done Checker
UnityEngine.AsyncOperation async = SceneManager.LoadSceneAsync(this.GetEnumDescription(sceneType));
// :: When Scene Load Completed
async.completed += Async_completed;

// :: Do Action
private void Async_completed(UnityEngine.AsyncOperation obj)
{
	if(obj.isDone)
	{
    	Debug.Log("Load Completed");
	}
}

 

블로그 이미지

RIsN

,