개발을 하다가 특정 Tag를 찾아 배열을 저장하는데

해당 Tag를 가진 Object가 하나도 없을경우 오류가 생기더라..

그래서 모든 오브젝트들의 Tag 검사를 해서 처리를 하려고 만들다가

발견한 방법


GameObject [] temp = FindObjectsOfType<GameObject>();


이런식으로 불러오면 되더라


끗!


여담으로 Tag로 Object를 찾는건


GameObject [] temp = GameObject.FindGameObjectsWithTag("Tag_Temp");


이렇게 했다.


그리고 기본적인 object찾기들
transform.Find("오브젝트 이름"); // 자식이나 부모 관계 안에서만 찾음
GameObject.Find("오브젝트 이름"); // Hierarchy안에서 다 찾음
GameObject.FindWithTag("태그 이름"); // 해당하는 태그에 속하는 오브젝트 반환.
                                        여러 개일 경우 그 중에 랜덤으로 반환


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

코루틴 사용법  (0) 2018.05.14
Unity Google 연동  (0) 2017.11.13
UI가 캐릭터를 따라가야할때 좌표 변환법  (0) 2017.10.26
간단한 AI FollowTarget Movement  (0) 2017.09.18
Unity 기본 Input Movement  (0) 2017.09.18

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

public class Model_AI_Default : MonoBehaviour {

    float m_fSpeed = 1f;

    bool isTarget = false;
    GameObject m_Target_Obj = null;

     

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        if (!isTarget) {
            if (FindNeedTarget ("Player"))
                isTarget = true;
            else
                isTarget = false;
        } else {
            GameObject CollMgr = GetCollisionCom ();
            bool isColl = CollMgr.GetComponent<CollisionComponent> ().Collision_Sphere (m_Target_Obj.transform.position, transform.position, 0.5f, 0.5f);
            if(isColl)
                FollowTarget ();
        }
    
    //  이렇게 써도 무방하다.
    //    if (FindNeedTarget ("Player"))
    //        FollowTarget ();
    }

    protected bool FindNeedTarget(string szTag)
    {
        // Target들을 찾는다
        GameObject[] Target_Arr = GameObject.FindGameObjectsWithTag (szTag);

        //Debug.Log (Target_Arr.Length);

        if (Target_Arr.Length == 0)
            return false;

        int iTargetNum = 0;
        float fDist_Ori = 0f;

        // 가장 가까운 target를 찾는다.
        for (int i = 0; i < Target_Arr.Length; ++i) {
            Vector3 vDist = Target_Arr [i].transform.position - transform.position;
            float fDist_New = vDist.magnitude;
            if (i == 0) {
                iTargetNum = i;
                fDist_Ori = fDist_New;
            } else {
                if (fDist_Ori > fDist_New) {
                    iTargetNum = i;
                    fDist_Ori = fDist_New;
                }
            }
        }
        m_Target_Obj = Target_Arr [iTargetNum];
        return true;
    }
    protected void FollowTarget()//target이 있으면 따라간다.
    {
        if (m_Target_Obj != null) {
            Vector3 vDir = m_Target_Obj.transform.position - transform.position;
            vDir = vDir.normalized;

            transform.Translate (vDir * m_fSpeed * Time.deltaTime, Space.World);
        }
    }

    protected GameObject GetCollisionCom()
    {
        return GameObject.Find ("ComponentMgr");
    }
}

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

코루틴 사용법  (0) 2018.05.14
Unity Google 연동  (0) 2017.11.13
UI가 캐릭터를 따라가야할때 좌표 변환법  (0) 2017.10.26
Scene의 모든 오브젝트 가져오는 법  (0) 2017.09.18
Unity 기본 Input Movement  (0) 2017.09.18

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

public class Model_Default : MonoBehaviour {

    float m_fSpeed = 3f;


    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        Default_Move_Input ();
        
    }

    protected void Default_Move_Input()
    {
        float fSpeedDelta = m_fSpeed * Time.deltaTime;
        Vector3 vDir = new Vector3 ();
        float fX = Input.GetAxis ("Horizontal");
        float fZ = Input.GetAxis ("Vertical");

        vDir.x = fX;
        vDir.z = fZ;
        vDir = vDir.normalized;

        transform.Translate (vDir * fSpeedDelta, Space.World);
    }
}

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

코루틴 사용법  (0) 2018.05.14
Unity Google 연동  (0) 2017.11.13
UI가 캐릭터를 따라가야할때 좌표 변환법  (0) 2017.10.26
Scene의 모든 오브젝트 가져오는 법  (0) 2017.09.18
간단한 AI FollowTarget Movement  (0) 2017.09.18

//while true false 사용

#include<stdio.h>

typedef enum { f, t } boolean;

void main()
{
 int n=0;
 boolean true = t;
 boolean false = f;
 while(true)
 {
  printf("학생의 번호 : %d\n",n);
  if(n==10)
   break;
  n++;
 }
}

 

//////////////////////

// bloolean 구현

#include<stdio.h>

typedef enum { false, true } boolean;

void main()
{
 int n=0;
 boolean limits = true;
 while(limits)
 {
  printf("학생의 번호 : %d\n",n);
  if(n==10)
   break;
  n++;
 }
}

 

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

sort  (0) 2017.09.18
수식계산기 v0.8  (0) 2017.09.18
수식계산기 v0.5  (0) 2017.09.18

// 원소(n)들을 (r)개씩 묶었을때 나오는 부분집합들 출력

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

void combination(char*, int, int, int, int, int*); // combination func..

int main()
{
    int i,j, number ,*array;
 //i = r  , number = n
 int c=0;//원소의 개수 = n
 int next =0;
 int nums = 0;
 char a[100] = {0};
 char *ap = a;
 char ar[21]={0};
 printf("수식[ex){a,s,d}3]을 입력하시오: ");
    gets(a);
 printf("input item number: ");
 
 for(j=0;j<100;j++)// 문자 & 숫자 걸러내기위한 부분
 {
  if((a[j]>=65&&a[j]<=90)||(a[j]>=97&&a[j]<=122))
  {
   ar[next]=a[j];
   next++;
  }
  else if((a[j]>=48&&a[j]<=57)||a[j]==0)
  {
   i=atoi(ap+j);
  break;
  }
 }
 while(1)// count 증가 부분
 {
  if(ar[c]==0)break;
  c++;}
  
 printf("%d\n",c);
 printf("%d",i);

 

    // create memory..
    array = (int*)malloc(sizeof(int)*(c+1));


        printf("\n* %d - combination >\n", i);
        combination(ar, 0, 0, i, c, array);

    printf("\n");

//    getch();
    free(array);   // free memory..
    return 0;
}

// recursive combination function..
void combination(char *ar, int now, int count, int step, int number, int* array)
{
    int i;

    *(array+count) = now;

    if (count == step)   // search r-combination ..
    {
        printf(" { %c", ar[*(array+1)-1]);   // print frist item..

        for (i = 2; i <= count; i++)
        {
            printf(", %c", ar[*(array+i)-1]);  // print other item..
        }

        printf(" } ");   // close..

        return ;
    }

    // recursive routine..
    for (i = now+1; i <= number; i++)
    {
        combination(ar, i, count+1, step, number, array);
    }
}

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

enum을 이용한 while( true or false ) 구현 과 boolean 구현  (0) 2017.09.18
수식계산기 v0.8  (0) 2017.09.18
수식계산기 v0.5  (0) 2017.09.18

//개발환경 visual studio 2010
//사칙연산 비교되는 Ver
#include <stdio.h>
#include <stdlib.h>

char n[100];
char cn[100];
int in[100];
char *pn=n;

int result=0,i,j=1,c=0;
int I,J,C;
 
char main()
{
 gets(n);
 //식별부
 in[0]=atoi(pn);
 for(i=0;i<=100;i++)
 {
  if(n[i]<=47&&n[i]>=40)
  {
  in[j]=atoi(pn+i+1);
  cn[c]=n[i];
  c++;
  j++;
  }
  else
  {}

 }
 for(I=0;I<=100;I++)//곱하기 나누기 연산부
 {
  if(cn[I]=='*'||cn[I]=='/')
  {
   if(cn[I]=='*')
   {
    in[I+1]=in[I]*in[I+1]; 
    in[I]=0;
    printf("%d ",in[I+1]);
   }
   if(cn[I]=='/')
   {
    in[I+1]=in[I]/in[I+1];
    in[I]=0;
    printf("%d ",in[I+1]);
   }
  }
  else{}
 }
 for(J=0;J<=100;J++)//빼기 변환부
 {
  if(cn[J]=='-')
  {
   if(in[J+1]==0)
   {
   in[J+2]= -in[J+2];
   printf("%d ",in[J+2]);
   }
   else
   {
   in[J+1]= -in[J+1];
   printf("%d ",in[J+1]);
   }
  }
 }
 for(C=0;C<=100;C++)//모두 더하기
 {
  result+=in[C];
 }
 printf("%d",result);
}

 

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

enum을 이용한 while( true or false ) 구현 과 boolean 구현  (0) 2017.09.18
sort  (0) 2017.09.18
수식계산기 v0.5  (0) 2017.09.18

//단순 4칙연산 수식 계산기
//입력: 124+324/4*3-2345     츨력: -2009.000000
//4칙연산 순서구분 없음
#include <stdio.h>
#include <stdlib.h>

char n[100];
char *pn=n;

int c;
double result=0,i=0,j;
 
char main()
{
 gets(n);
 result+=atoi(pn);
 for(c=0;c<=100;c++)
 {
  if(n[c]=='-')
  {
   j=atoi(pn+c+1);
   result-=j;
   printf("%lf\n",result);

  }
  else if(n[c]=='+')
  {
   j=atoi(pn+c+1);
   result+=j;
   printf("%lf\n",result);
  }
  else if(n[c]=='*')
  {
   j=atoi(pn+c+1);
   result*=j;
   printf("%lf\n",result);
  }
  else if(n[c]=='/')
  {
   if(j==0)
   {
   result=0;
   printf("%lf\n",result);
   }
   else{
   j=atoi(pn+c+1);
   result/=j;
   printf("%lf\n",result);}   
  }
  else
  {}
 }
}

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

enum을 이용한 while( true or false ) 구현 과 boolean 구현  (0) 2017.09.18
sort  (0) 2017.09.18
수식계산기 v0.8  (0) 2017.09.18

재대후 처음 자바를 공부하면서 만든 간단한 Java 계산기 프로그램

//Main

package calculator;

import java.util.Scanner;

public class CalMain {

public static void main(String[] args) {

double num1;
double num2;
double result;

Cal cal= new Cal();
Scanner input=new Scanner(System.in);
String c="@";
System.out.println("숫자를 입력해 주세요 :\t");
num1 = input.nextDouble();
do{
if(c=="#")
break ;
System.out.println("연산자 :\t");
c=input.next();
System.out.println("숫자를 입력해주세요\t");
num2=input.nextDouble();
System.out.println("결과값 :\t");
switch(c){
case "+":
result = cal.add(num1, num2);
System.out.println(result);
num1=result;
break;
case "-":
result = cal.minus(num1, num2);
System.out.println(result);
num1=result;
break;
case "*":
result = cal.multi(num1, num2); 
System.out.println(result);
num1=result;
break;
case "/":
result = cal.division(num1, num2);
System.out.println(result);
num1=result;
break;
case "c":
System.out.println("초기화\t");
System.out.println("숫자를 입력해주세요\t");
num1 = input.nextDouble();
break;
case "#":
System.out.println("끝\t");
c="#";
break;
default:
System.out.println("잘못된 연산입니다 연산자부터 다시 입력해 주세요\t");
break ;
}
}while(true);

}

}

//////////////////////////////////////////////////////////////////////////

//Class

package calculator;

public class Cal {
double result;

double add(double num1, double num2){
result = num1 + num2;
return result;
}
double minus(double num1, double num2){
result = num1 - num2;
return result;
}
double multi(double num1, double num2){
result = num1 * num2;
return result;
}
double division(double num1, double num2){
result = num1 / num2;
return result;
}
double clear(){
result = 0;
return result;
}
}
////////////////////////////////////////////////////////////////////

뼈대만 만들었다 자잘한건 아직....



유니티를 개발하게 되면서 IEnumerator와 IEnumerable에 대해 공부하게되었다.


간단하게 요약하자면 Custom한 state를 만들어 while이나 foreach문으로 편리하게 쓰거나 Coroutine으로 사용하는

Interface의 일종  


IEnumerator가 가지는 state의 초기값은 -1이다.



사용하는 방법을 코드로 풀어보면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private int[] data = { 5, 4, 3, 2, 1 };
 
public IEnumerator GetEnumerator()
{
    int i = 0;
    while (i < data.Length)
    {
        Debug.Log(data[i]);    //MoveNext.했을때 진행이 끝나는 지점.
        yield return data[i];    //Current에 접근했을때 진행이 끝나는 지점
        ++i;
    }
}
 
private void Start()
{
    IEnumerator it = data.GetEnumerator();
 
    it.MoveNext(); // 내부적인 state가 이때 -1에서 0이 된다.
    Debug.Log(it.Current);    // data[i]의(i = 0) 값인 5가 리턴되어 나오고
    it.MoveNext();
    Debug.Log(it.Current);    // data[i]의(i = 1) 값인 4이 리턴되어 나오고
    it.MoveNext();
    Debug.Log(it.Current);    // data[i]의(i = 2) 값인 3이 리턴되어 나온다
}


C#에서 list들은

IEnumerator를 원래 가지고있어

(int[] dat = { 1, 2, 3, 4, 5 };

dat.GetEnumerator(); //이렇게 나온다)


IEnumerator를 만들어 주지 않아도 된다.(위의 GetEnumerator는 대충 어떻게 동작하는지 보여주기 위한 구현)


IEnumerator를 사용하는 반복문의 2가지 예

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private int[] data = { 5, 4, 3, 2, 1 };
 
//예_1
IEnumerator it = data.GetEnumerator();
while(it.MoveNext())
{
    Debug.Log(it.Current);
}
 
//예_2
foreach(var num in data)
{
    Debug.Log(num);
}


그리고 IEnumerable 이라고


public IEnumerable<int> GetNumber()

    {

        int i = 0;

        while (i < data.Length)

        {

            yield return data[i];

            ++i;

        }

    }

해서

foreach (int num in GetNumber())

{

    Debug.Log(num);

}

이렇게 쓰는 방법도 있다.


다시 돌아와서 IEnumerator를 코루틴으로 돌리면

StartCoroutine(GetEnumerator());//이렇게 하면 되고 이때 쓰는 GetEnumerator()는 만들어 줘야함

물론  StartCoroutine(data.GetEnumerator());//이렇게 쓰면 안만들어줘도 된다.


하지만 커스텀 하고싶으면 위의 GetEnumerator()처럼

IEnumerator 만들어서 입맛대로 yield return 해줘야 된다.

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

return default(T);란?  (0) 2018.08.02
C# string 사용법  (0) 2018.06.27
C# const, readonly 차이  (0) 2018.06.04
C# 문법 참고 사이트  (0) 2018.06.01
C# 자료구조별 속도  (0) 2018.03.20

+ Recent posts