반응형

씬에 있는 비활성화된 오브젝트는 FindXXX()로 직접 찾을 수 없다. 하지만 부모 오브젝트가 있는 자식 오브젝트라면 부모 오브젝트를 먼저 찾고 transform 컴포넌트의 Find(), GetChild() 등으로 찾을 수 있다.

 

부모 오브젝트(Parent) 아래에 자식 오브젝트(1st, 2nd)를 만든다.

 

자식 오브젝트(1st, 2nd)는 비활성화 시킨다.

 

적당한 스크립트에 비활성화된 자식 오브젝트를 찾는 코드를 입력한다.

 

찾은 자식 오브젝트의 이름이 출력된다.

 

반응형
Posted by J-sean
:
반응형

유니티 3D를 실행하면 Directional Light가 하나 추가 되어 있다.

 

Directional Light의 기본 세팅

 

기본 Directional Light의 영향으로 모든 오브젝트에 빛이 비춘다.

 

하지만 Directional Light를 끄면 완전히 어두워질 거라는 예상과 다르게 빛이 남아 있다.

어디에서 빛이 비추는지 찾아 보자.

 

Window - Rendering - Lighting

 

 

Environment 탭을 확인하면 Skybox부터 Environment Lighting, Environment Reflections 등의 세팅을 확인할 수 있다.

 

Environment Lighting - Intensity Multiplier 및 Environment Refections - Intensity Multiplier를 0으로 세팅한다.

 

완전히 어두워졌다.

 

그 외, Skybox Material등의 설정도 바꿀 수 있다.

 

반응형
Posted by J-sean
:
반응형

상하좌우로 방향을 전환하는 컨트롤러 스크립트를 만들어 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Controller : MonoBehaviour
{
    private Rigidbody m_rigidbody;
    public float speed = 3f;
 
    // Start is called before the first frame update
    void Start()
    {
        m_rigidbody = GetComponent<Rigidbody>();
    }
    
    // Update is called once per frame
    void Update()
    {
        if (GameManager.instance.isGameover)
            return;
 
        float xInput = Input.GetAxis("Horizontal");
        float zInput = Input.GetAxis("Vertical");
 
        float xSpeed = xInput * speed;
        float zSpeed = zInput * speed;
 
        Vector3 newVelocity = new Vector3(xSpeed, 0f, zSpeed);
        m_rigidbody.velocity = newVelocity;
        
        if (xInput > 0)
        {
            transform.rotation = Quaternion.Euler(new Vector3(0f, 180f, 0f));
        }
        else if (xInput < 0)
        {
            transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, 0f));
        }
        else if (zInput > 0)
        {
            transform.rotation = Quaternion.Euler(new Vector3(0f, 90f, 0f));
        }
        else if (zInput < 0)
        {
            transform.rotation = Quaternion.Euler(new Vector3(0f, 270f, 0f));
        }
    }
}
 

 

팩맨이 움직이는 방향으로 회전한다.

 

반응형
Posted by J-sean
:
반응형

텍스트 파일로 간단한 맵을 생성해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Spawner : MonoBehaviour
{
    public GameObject[] objects;    
 
    // Start is called before the first frame update
    void Start()
    {
        string path = Application.dataPath + "/Map.txt";
        string[] map = System.IO.File.ReadAllLines(path);
 
        if (map.Length > 0)
        {
            for (int i=0; i<map.Length; i++)
            {
                for (int j=0; j<map[i].Length; j++)
                {
                    if (map[i][j] != ' ')
                        Instantiate(objects[int.Parse(map[i][j].ToString())], new Vector3(-(i * 1), 0-(j * 1)), Quaternion.identity);
                        //Instantiate(objects[(int)char.GetNumericValue(map[i][j])], new Vector3(-(i * 1), 0, -(j * 1)), Quaternion.identity);
                    
                }
            }
        }
    }
}
 

위 스크립를 작성하고 Empty Object에 추가한다.

Map.txt
0.00MB

Assets 폴더에 Map.txt 파일을 준비한다.

0: 큐브, 1: 스피어

 

스크립트가 추가된 오브젝트의 Inspector 창에서 Objects에 미리 준비한 Cube, Sphere 오브젝트를 추가한다.

 

간단한 미로맵이 완성 되었다.

 

반응형
Posted by J-sean
:
반응형

텍스트 파일을 읽고 내용을 출력해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class TextReader : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        string path = Application.dataPath;    // D:/UnityTest/My project/Assets
        path += "/Text/Text.txt";    // D:/UnityTest/My project/Assets/Text/Text.txt
 
        /* Text 파일 내용
        First text line.
        Second text line.
        Third text line.
        Fourth text line.
        Fifth text line.
        1,2,3,4,5
        6,7,8,9,10
        */
 
        string[] contents = System.IO.File.ReadAllLines(path);
        if (contents.Length > 0)
        {
            for (int i=0; i<contents.Length; i++)
            {
                if (i < 5)
                {
                    Debug.Log(contents[i]);
                }
                else // 숫자 텍스트
                {
                    string[] txtArr = contents[i].Split(',');
                    int[] numArr = new int[txtArr.Length];
                    int total = 0;
 
                    for (int j=0; j<txtArr.Length; j++)
                    {
                        numArr[j] = int.Parse(txtArr[j]);
                        total += numArr[j];
                    }
 
                    Debug.Log(total);
                }
            }
        }
 
        string content = System.IO.File.ReadAllText(path);
        Debug.Log(content);
    }
}
 

 

 

반응형
Posted by J-sean
:
반응형

DOTween의 DOPath() 예제


아래와 같은 스크립트를 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
 
public class Tween : MonoBehaviour
{
    public Ease ease;
 
    public Transform wayPoint1;
    public Transform wayPoint2;
    public Transform wayPoint3;
 
    private Vector3[] wayPoints;
 
    // Start is called before the first frame update
    void Start()
    {
        // static DOTween.Init(bool recycleAllByDefault = false, bool useSafeMode = true, LogBehaviour logBehaviour = LogBehaviour.ErrorsOnly)
        // Initializes DOTween.
        DOTween.Init(falsetrue, LogBehaviour.ErrorsOnly);
 
        wayPoints = new Vector3[3];
        wayPoints.SetValue(wayPoint1.position, 0);
        wayPoints.SetValue(wayPoint2.position, 1);
        wayPoints.SetValue(wayPoint3.position, 2);
        // wayPoints = new[] { wayPoint1.position, wayPoint2.position, wayPoint3.position };
 
        // DOPath(Vector3[] waypoints, float duration, PathType pathType = Linear, PathMode pathMode = Full3D, int resolution = 10, Color gizmoColor = null)
        // Tweens a Transform's position through the given path waypoints, using the chosen path algorithm.
        transform.DOPath(wayPoints, 6.0f, PathType.CatmullRom).SetLookAt(new Vector3(0.0f, 0.0f, 0.0f)).SetEase(ease).SetLoops(-1, LoopType.Yoyo);
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}
 


스크립트 이름은 Tween으로 지정 한다.


Empty Object(WayPoint)와 Cube를 생성하고 Cube에 Tween 스크립트를 추가한다.


Empty Object를 3개 생성하고 WayPointX로 이름을 바꿔서 Cube가 이동할 위치에 배치한다. Cube Inspector 창의 Tween 스크립트에서 Way Point1~3 변수에 WayPoint1~3 오브젝트를 지정한다. Ease 변수도 In Bounce 등 원하는 ease로 변경한다.


플레이 버튼을 클릭 하면 Cube가 지정한 위치들을 거쳐 이동 한다. DOPath()의 경우 Scene창에 이동 경로가 표시 된다.


반응형
Posted by J-sean
:
반응형

DOTween의 Sequence 예제


아래와 같은 스크립트를 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
 
public class Tween : MonoBehaviour
{
    public Ease ease;
 
    // Start is called before the first frame update
    void Start()
    {
        // static DOTween.Init(bool recycleAllByDefault = false, bool useSafeMode = true, LogBehaviour logBehaviour = LogBehaviour.ErrorsOnly)
        // Initializes DOTween.
        DOTween.Init(falsetrue, LogBehaviour.ErrorsOnly);
 
        // static DOTween.Sequence()
        // Returns a usable Sequence which you can store and add tweens to.
        Sequence mySeq = DOTween.Sequence();
 
        // Delays and loops (when not infinite) will work even inside nested tweens.
 
        // Append(Tween tween)
        // Adds the given tween to the end of the Sequence.
        mySeq.Append(transform.DOMove(new Vector3(5.0f, 0.0f, 5.0f), 2false).SetEase(ease).SetLoops(3, LoopType.Yoyo));
        mySeq.Append(transform.DOMove(new Vector3(-5.0f, 0.0f, 5.0f), 2false).SetEase(ease).SetLoops(3, LoopType.Yoyo));
        // 첫 번째 DOMove를 3회 반복, 그리고 두 번째 DOMove를 3회 반복 한다. 전체(첫 번째 + 두 번째) DOMove를 3회 반복하는게 아니다.
 
        // Insert a lookat tween for the whole duration of the Sequence
 
        // Insert(float atPosition, Tween tween)
        // Inserts the given tween at the given time position, thus allowing you to overlap tweens instead of just placing them one after each other.
        mySeq.Insert(0, transform.DOLookAt(new Vector3(0.0f, 0.0f, 0.0f), mySeq.Duration()));
        // float Duration(bool includeLoops = true)
        // Returns the duration of the tween(delays excluded, loops included if includeLoops is TRUE).
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}
 


스크립트 이름은 Tween으로 지정 한다.


Cube를 생성하고 Tween 스크립트를 추가한다.


Inspector 창의 Tween 스크립트에서 Ease 변수를 In Bounce 등 원하는 ease로 변경한다.


플레이 버튼을 클릭 하면 Cube가 첫 번째 DOMove 3회, 두 번째 DOMove 3회를 반복하며 전체 시간에 걸쳐 원점을 향해 회전 한다.


반응형
Posted by J-sean
:
반응형

DOTween의 DOMove(), DOColor() 예제


아래와 같은 스크립트를 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
 
public class Tween : MonoBehaviour
{
    public Ease ease;
 
    // Start is called before the first frame update
    void Start()
    {
        // static DOTween.Init(bool recycleAllByDefault = false, bool useSafeMode = true, LogBehaviour logBehaviour = LogBehaviour.ErrorsOnly)
        // Initializes DOTween.
        DOTween.Init(falsetrue, LogBehaviour.ErrorsOnly);
 
        // DOMove(Vector3 to, float duration, bool snapping)
        // Moves the target's position to the given value.
        transform.DOMove(new Vector3(0.0f, 0.0f, 5.0f), 3.0f, false).SetEase(ease).SetLoops(-1, LoopType.Yoyo);
 
        // DOColor(Color to, float duration)
        // Changes the target's color to the given one.
        transform.GetComponent<MeshRenderer>().material.DOColor(Color.red, 3.0f).SetLoops(-1, LoopType.Yoyo);
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 


스크립트 이름은 Tween으로 지정 한다.


Cube를 생성하고 Tween 스크립트를 추가한다.


Inspector 창의 Tween 스크립트에서 Ease 변수를 In Bounce 등 원하는 ease로 변경한다.


플레이 버튼을 클릭 하면 Cube가 지정한 동작으로 움직이며 색깔이 변경 된다.

반응형
Posted by J-sean
: