string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";

Console.WriteLine(GetWeatherDisplay(15));  // output: Cold.
Console.WriteLine(GetWeatherDisplay(27));  // output: Perfect!

이 코드에서 tempInCelsius < 20.0이 조건입니다. 사실이면 "Cold"로, 거짓이면 "Perfect!"로 인쇄됩니다.

condition ? A : B

조건이 사실이면 A를 선택합니다.
조건이 거짓이면 B에 해당합니다.

 

난수 예제를 사용한 분석은 다음과 같다:

var rand = new Random();
var condition = rand.NextDouble() > 0.5;

int? x = condition ? 12 : null;

IEnumerable<int> xs = x is null ? new List<int>() { 0, 1 } : new int[] { 2, 3 };

조건이 참이면 x는 값 12를 얻고, 거짓이면 null이 된다.
그런 다음 x가 null인지 아닌지에 따라 x는 다른 컬렉션을 할당받는다.

이 문구를 기억하세요: 
"이 조건이 사실인가요? 네, 그럼 이렇게 하세요; 아니요, 그럼 그렇게 하세요."

 

int[] smallArray = { 1, 2, 3, 4, 5 };
int[] largeArray = { 10, 20, 30, 40, 50 };

int index = 7;
ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);
refValue = 0;

index = 2;
((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100;

여기서 refValue는 조건에 따라 smallArray 또는 largeArray에 있는 요소에 대한 참조입니다.

 

언제 사용해야 하는지:
조건부 연산자를 사용하면 한 줄에 값을 할당하고 결정을 내리고 싶을 때 코드를 더 간결하게 만들 수 있습니다.

 

if 문을 사용한 예제:

int input = new Random().Next(-5, 5);

string classify;
if (input >= 0)
{
    classify = "양수";
}
else
{
    classify = "음수";
}

 

조건부 연산자를 사용하면 이와 동일합니다:

classify = (input >= 0) ? "양수" : "음수";

입력값이 0보다 크거나 같으면 비음수이고, 그렇지 않으면 negative입니다."라고 말하는 것과 같습니다

 

출처: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

 

string clickedButtonName = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name;
Debug.Log(clickedButtonName);

'프로그래밍' 카테고리의 다른 글

C# 조건부 연산자 ?:  (1) 2023.12.21
C# LINQ 그림으로 설명  (0) 2022.08.08
유니티 토글 그룹에서 선택된 토글 가져오기  (0) 2021.01.28
XML 개행문자  (0) 2021.01.15
C# XML 읽어오기  (0) 2020.12.01

 

 

 

출처: https://steven-giesel.com/blogPost/d65c5411-a69b-489f-b73f-18ce0ed8678d?utm_source=csharpdigest&utm_medium=email&utm_campaign=427

런타임 모니터링은 런타임 중에 C# 멤버의 값이나 상태를 쉽게 모니터링할 수 있는 방법입니다. 필드, 속성, 이벤트 또는 메서드에 [Monitor] 속성을 추가하기만 하면 해당 값이나 상태가 사용자 지정 및 확장 가능한 UI에 자동으로 표시됩니다.

링크https://github.com/JohnBaracuda/com.baracuda.runtime-monitoring?tab=readme-ov-file

function onOpen() {
    sortSheetsByName();
}
function sortSheetsByName() {
    var aSheets = new Array();
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    for (var s in ss.getSheets()) {
        aSheets.push(ss.getSheets()[s].getName());
    }
    if (aSheets.length) {
        aSheets.sort();
        for (var i = 0; i < aSheets.length; i++) {
            var theSheet = ss.getSheetByName(aSheets[i]);
            if (theSheet.getIndex() != i + 1) {
                ss.setActiveSheet(theSheet);
                ss.moveActiveSheet(i + 1);
            }
        }
    }
}​
스크립트 저장 후 파일을 열면 바로 실행 됨.

출처: https://support.google.com/docs/thread/2806598/any-way-to-sort-sheets-in-alphabetical-order-in-my-workbook?hl=en

using System.Linq;

void Example()
{
	Toggle theActiveToggle = toggleGroup.ActiveToggles().FirstOrDefault();
}

 

'프로그래밍' 카테고리의 다른 글

유니티 버튼 클릭했을때 버튼 이름 가져오기  (0) 2022.12.15
C# LINQ 그림으로 설명  (0) 2022.08.08
XML 개행문자  (0) 2021.01.15
C# XML 읽어오기  (0) 2020.12.01
C# DateTime 포맷  (0) 2020.09.02
SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();

if (spriteRenderer == null)
	return;

gameObject.transform.localScale = new Vector3(1, 1, 1);

float _width = spriteRenderer.bounds.size.x;
float _height = spriteRenderer.bounds.size.y;

float worldScreenHeight = (float)(Camera.main.orthographicSize * 2.0);
float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;


gameObject.transform.localScale = new Vector3(worldScreenWidth / _width, worldScreenHeight/_height,1);

출처: answers.unity.com/questions/620699/scaling-my-background-sprite-to-fill-screen-2d-1.html

C#에서 XML 가져올 때 XML 내부 내용 개행

 

&#xA;

<Title>첫 번째 줄입니다.&#xA;두 번째 줄입니다.</Title>

=>

첫 번째 줄입니다.

두 번째 줄입니다.

 

 

string _path = @"C:/Test.xml";

XmlDocument Document = new XmlDocument();
Document.Load(_path);

XmlNodeList xmlNodeList = Document.SelectNodes("TestList");

 

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}",      dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}",      dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}",      dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",          dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",               dt);  // "5 05"            minute
String.Format("{0:s ss}",               dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}",      dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}",      dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",               dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",           dt);  // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}",           dt);  // "3/9/2008"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}",   dt);  // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}",           dt);  // "03/09/08"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"


String.Format("{0:t}", dt);  // "4:05 PM"                           ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                          ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                        LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"            LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"    LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                  ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"               ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                          MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                       YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"     RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"               SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"              UniversalSortableDateTime

/*
Specifier   DateTimeFormatInfo property     Pattern value (for en-US culture)
    t           ShortTimePattern                    h:mm tt
    d           ShortDatePattern                    M/d/yyyy
    T           LongTimePattern                     h:mm:ss tt
    D           LongDatePattern                     dddd, MMMM dd, yyyy
    f           (combination of D and t)            dddd, MMMM dd, yyyy h:mm tt
    F           FullDateTimePattern                 dddd, MMMM dd, yyyy h:mm:ss tt
    g           (combination of d and t)            M/d/yyyy h:mm tt
    G           (combination of d and T)            M/d/yyyy h:mm:ss tt
    m, M        MonthDayPattern                     MMMM dd
    y, Y        YearMonthPattern                    MMMM, yyyy
    r, R        RFC1123Pattern                      ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
    s           SortableDateTi­mePattern             yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
    u           UniversalSorta­bleDateTimePat­tern    yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
                                                    (*) = culture independent   
*/

# using c# 6 string interpolation format
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

$"{dt:y yy yyy yyyy}";  // "8 08 008 2008"   year
$"{dt:M MM MMM MMMM}";  // "3 03 Mar March"  month
$"{dt:d dd ddd dddd}";  // "9 09 Sun Sunday" day
$"{dt:h hh H HH}";      // "4 04 16 16"      hour 12/24
$"{dt:m mm}";           // "5 05"            minute
$"{dt:s ss}";           // "7 07"            second
$"{dt:f ff fff ffff}";  // "1 12 123 1230"   sec.fraction
$"{dt:F FF FFF FFFF}";  // "1 12 123 123"    without zeroes
$"{dt:t tt}";           // "P PM"            A.M. or P.M.
$"{dt:z zz zzz}";       // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}";    // "3/9/2008"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

// day/month names
$"{dt:ddd, MMM d, yyyy}";    // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}";  // "Sunday, March 9, 2008"

// two/four digit year
$"{dt:MM/dd/yy}";    // "03/09/08"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

 

출처:https://stackoverflow.com/questions/3025361/c-sharp-datetime-to-yyyymmddhhmmss-format

AudioClip recordClip;

void StartRecordMicrophone()
{
	recordClip = Microphone.Start("Built-in Microphone", true, 100, 44100);
}

void StopRecordMicrophone()
{
	int lastTime = Microphone.GetPosition(null);

	if (lastTime == 0)
		return;
	else
	{
		Microphone.End(Microphone.devices[0]);

		float[] samples = new float[recordClip.samples];

		recordClip.GetData(samples, 0);

		float[] cutSamples = new float[lastTime];

		Array.Copy(samples, cutSamples, cutSamples.Length - 1);

		recordClip = AudioClip.Create("Notice", cutSamples.Length, 1, 44100, false);

		recordClip.SetData(cutSamples, 0);
	}
}

 

Microphone.Start으로 하면 길이를 정하고 녹음이 됨

그래서 Microphone.End 했을때 길이까지만 녹음되게 함

혹시 다른 방법있으시면 댓글 남겨주세요.

public class MyClass
{
    public string _datafile;

    public MyClass()
    {
        _datafile = "Hello";
    }

    public void PrintField()
    {
        var result = this.GetType().GetField("_datafile").GetValue(this); 
        Console.WriteLine(result); // will print Hello
    }
}

 

public string[] temp1 = new string[3]
{
	"A","B","C"
};

public string[] temp2 = new string[3]
{
	"D","E","F"
};

public string[] temp3 = new string[3]
{
	"G","H","I"
};

void GetValue()
{
	string[] tempArray = (string[])GetType().GetField("temp1").GetValue(this);

	Debug.Log("A: " + string.Join(",", tempArray));
}

 


https://stackoverflow.com/questions/11122241/accessing-a-variable-using-a-string-containing-the-variables-name

// 문자열 -> int 리스트

string sNumbers = "1,2,3,4,5";
List<int> numbers = new List<int>();
umbers = sNumbers.Split(',').Select(Int32.Parse).ToList();

// 문자열 -> int 배열
string sNumbers = "1,2,3,4,5";
int[] numbers = sNumbers.Split(',').Select(n => Convert.ToInt32(n)).ToArray();

출처: https://stackoverflow.com/questions/911717/split-string-convert-tolistint-in-one-line

 

 

300x300 크기의 이미지에서 정중앙에 클릭하면 150,150의 좌표를 가져옴(피벗이 0,0 기준)

왼쪽 최하단을 클릭하면 0,0의 좌표를 가져옴.

public void OnPointerClick(PointerEventData eventData)
{
	if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), 
		eventData.position, eventData.pressEventCamera, out Vector2 localCursor))
		return;

	Debug.Log("LocalCursor:" + localCursor);
}

 

출처: https://answers.unity.com/questions/892333/find-xy-cordinates-of-click-on-uiimage-new-gui-sys.html

+ Recent posts