'C#/Study'에 해당되는 글 14건

  1. 2019.12.18 Sprite Atlas 사용하기
  2. 2019.12.16 오브젝트 풀링 (인스턴스로 접근)
  3. 2019.12.10 12.10 오브젝트 풀 활용
  4. 2019.12.09 12.09 드래곤플라이트 2 (이펙트 추가)
  5. 2019.12.02 12.02 객체 충돌
  6. 2019.11.02 struct 와 클래스의 차이
  7. 2019.10.31 ref 와 out
  8. 2019.10.31 초기화

Sprite Atlas 사용하기

C#/Study 2019. 12. 18. 16:54

추가:

Atlas 사용하기:

0. Edit > Project Setting > Editor> Sprite Packer > Mode = Always Enabled

1. 프로젝트 폴더 우클릭해서 Create > Sprite Atlas 생성

2. (인스펙터를 잠금한 후)Objects for Packing에 넣을 스프라이트들을 드래그하여 넣는다. 

(Pack Preview 클릭하면 미리보기 가능)

3. 코드창에 

추가:

using UnityEngine.U2D;

선언:
public SpriteAtlas atlas;

사용:

atlas.GetSprite(이름);

(atlas 안에 있는 스프라이트를 꺼내온다)

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

오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.10 오브젝트 풀 활용  (0) 2019.12.10
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
:

오브젝트 풀링 (인스턴스로 접근)

C#/Study 2019. 12. 16. 10:06
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class objectPool : MonoBehaviour
{
    private List<Bullet> bullets;
    private GameObject bulletPrefab;
    public void Init(GameObject bulletprefab) //Init을 해줘야한다!
    {
        this.bullets = new List<Bullet>();
        this.bulletPrefab = bulletprefab;
    }
    public void PreLoad()//만들기
    {
        for(int i =0; i<10; i++)
        {
            var bulletGo = Instantiate<GameObject>(this.bulletPrefab);
            bulletGo.transform.SetParent(this.transform, false);
            bulletGo.transform.localPosition = Vector3.zero;
            bulletGo.SetActive(false);
            var bullet = bulletGo.GetComponent<Bullet>();
            this.bullets.Add(bullet);
        }
    }
    public Bullet GetBullet() //꺼내기
    {
        Bullet bullet = null;
        if (this.bullets.Count > 0)
        {
            bullet = this.bullets[0];
            this.bullets.RemoveAt(0);
            bullet.gameObject.SetActive(true);
            bullet.transform.SetParent(null);
        }
        else
        {
            //재사용할 총알 없음
            bullet = Instantiate<GameObject>(this.bulletPrefab).GetComponent<Bullet>();           
        }
        return bullet;
    }
    public void Release(Bullet bullet) // 넣기
    {
        bullet.transform.SetParent(this.transform, false);
        bullet.transform.localPosition = Vector3.zero;
        bullet.gameObject.SetActive(false);
        this.bullets.Add(bullet);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

App 클래스에서 퍼블릭 멤버 변수로 선언하여 사용한다.

 

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

Sprite Atlas 사용하기  (0) 2019.12.18
12.10 오브젝트 풀 활용  (0) 2019.12.10
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
:

12.10 오브젝트 풀 활용

C#/Study 2019. 12. 10. 16:47

코드:

 

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 App : MonoBehaviour
{
    public Button btn;
    public GameObject bulletPrefab;
    public objectPool objectPool;
    // Start is called before the first frame update
    void Start()
    {
        this.objectPool.Init(this.bulletPrefab);
        this.objectPool.PreLoad();
 
        btn.onClick.AddListener(() => {
            var bullet = this.objectPool.GetBullet();
            var initPos = new Vector3(001);
            bullet.Init(initPos);
            bullet.onDestroy = () =>
            {
                objectPool.Release(bullet);
            };
        });
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    public float speed =3.5f;
    public System.Action onDestroy;
    private Coroutine coroutine;
    public void Init(Vector3 initPos)
    {
        this.transform.position = initPos;
        this.gameObject.SetActive(true);
        this.Move();
    }
    public void Move()
    {
        coroutine = this.StartCoroutine(this.MoveImpl());
    }
    public IEnumerator MoveImpl()
    {
        while(true)
        {
            this.transform.Translate(Vector3.up * this.speed * Time.deltaTime);            
            yield return null;
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.LogFormat("OnTriggerEnter2D:{0}", collision);
        StopCoroutine(coroutine);
        this.onDestroy();
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class objectPool : MonoBehaviour
{
    private List<Bullet> bullets;
    private GameObject bulletPrefab;
    public void Init(GameObject bulletprefab)
    {
        this.bullets = new List<Bullet>();
        this.bulletPrefab = bulletprefab;
    }
    public void PreLoad()//만들기
    {
        for(int i =0; i<10; i++)
        {
            var bulletGo = Instantiate<GameObject>(this.bulletPrefab);
            bulletGo.transform.SetParent(this.transform, false);
            bulletGo.transform.localPosition = Vector3.zero;
            bulletGo.SetActive(false);
            var bullet = bulletGo.GetComponent<Bullet>();
            this.bullets.Add(bullet);
        }
    }
    public Bullet GetBullet() //꺼내기
    {
        Bullet bullet = null;
        if (this.bullets.Count > 0)
        {
            bullet = this.bullets[0];
            this.bullets.RemoveAt(0);
            bullet.gameObject.SetActive(true);
            bullet.transform.SetParent(null);
        }
        else
        {
            //재사용할 총알 없음
            bullet = Instantiate<GameObject>(this.bulletPrefab).GetComponent<Bullet>();           
        }
        return bullet;
    }
    public void Release(Bullet bullet) // 넣기
    {
        bullet.transform.SetParent(this.transform, false);
        bullet.transform.localPosition = Vector3.zero;
        bullet.gameObject.SetActive(false);
        this.bullets.Add(bullet);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

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

Sprite Atlas 사용하기  (0) 2019.12.18
오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
:

12.09 드래곤플라이트 2 (이펙트 추가)

C#/Study 2019. 12. 9. 22:15

 

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public Ship ship;
    public Button CreateEnemy;
    public Button CreateShip;
    private bool enemyExist = false;
    private GameObject enemyPrefab;
    public static GameObject bulletPrefab;
    public static GameObject explosion;
    private GameObject shipPrefab;
    // Start is called before the first frame update
    private void Awake()
    {
        bulletPrefab = Resources.Load<GameObject>("fireball-blue-med");
        enemyPrefab = Resources.Load<GameObject>("ship1");
        shipPrefab = Resources.Load<GameObject>("ship2");
        explosion = Resources.Load<GameObject>("Animations/Explosion");
    }
    void Start()
    {
        CreateShip.onClick.AddListener(() =>
        {
            if(GameObject.Find("Ship"== null)
            {
                GameObject shipGO = new GameObject("Ship");
                ship = shipGO.AddComponent<Ship>();
                var model = Instantiate(shipPrefab);
                ship.transform.position = new Vector3(0-1.237f, -1.7045f);
                model.transform.SetParent(shipGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                model.transform.localRotation = Quaternion.Euler(new Vector3(00, 180f));
            }
        });
        CreateEnemy.onClick.AddListener(() => //enemy 생성
        {
            if(!enemyExist)
            {
                float x = 1;
                for (int i = 0; i<5; i++)
                {
                    
                    GameObject enemyGO = new GameObject("enemy");
                    Enemy enemy = enemyGO.AddComponent<Enemy>();
                    enemyGO.transform.position = new Vector3(x, 3.38f, -1.7045f);
                    var model = Instantiate(enemyPrefab);
                    model.transform.SetParent(enemyGO.transform, false);
                    model.transform.localPosition = Vector3.zero;
                    enemy.model = model;                    
                    enemy.Attack();
                    x -= 0.5f;
                }
                enemyExist = true;
                
            }
        });
    }
 
    // Update is called once per frame
    void Update()
    {        
        if(GameObject.Find("enemy"== null)
        {
            enemyExist = false;
        }        
        if(ship != null)
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                if (ship.transform.position.x >= -1.96f)
                {
                    ship.transform.position += Vector3.left * 2 * Time.deltaTime;
                }
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                if (ship.transform.position.x <= 1.96f)
                    ship.transform.position += Vector3.right * 2 * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.UpArrow))
            {
                if (ship.transform.position.y <= 4.4f)
                    ship.transform.position += Vector3.up * 2 * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.DownArrow))
            {
                if (ship.transform.position.y >= -1.7f)
                    ship.transform.position += Vector3.down * 2 * Time.deltaTime;
            }
            if (Input.GetKeyDown(KeyCode.Space))
            {
                GameObject bulletGO = new GameObject("Bullet");
                bulletGO.transform.position = ship.bulletInitPoint.transform.position;
                Bullet bullet = bulletGO.AddComponent<Bullet>();
                var model = Instantiate(App.bulletPrefab);
                model.transform.SetParent(bulletGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                bullet.GoTo();
            }
        }
        
         
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ship : MonoBehaviour
{
    public GameObject bulletInitPoint;
 
    // Start is called before the first frame update
    void Start()
    {
        bulletInitPoint = new GameObject("bulletInitPoint");
        bulletInitPoint.transform.SetParent(this.transform, false);
        bulletInitPoint.transform.localPosition = new Vector3(00.4f, 0);
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.153413f, 0.46f, 1f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
    }
    private void OnTriggerEnter(Collider other)
    {
        Destroy(this.gameObject);
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
53
54
55
56
57
58
59
60
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Enemy : MonoBehaviour
{
    public Vector3 target;
    public GameObject model;
    private GameObject bulletInitPoint;
    // Start is called before the first frame update
    private void Awake()
    {
        bulletInitPoint = new GameObject("bulletInitPoint");
        bulletInitPoint.transform.SetParent(this.transform, false);
        bulletInitPoint.transform.localPosition = new Vector3(0-0.25f, 0);
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.3373507f, 0.34f, 0.2f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
    }
    private void OnTriggerEnter(Collider other)
    {
        Destroy(this.gameObject);
    }
    void Start()
    {
        
    }
    public void Attack()
    {
        StartCoroutine(AttackC());
    }
    IEnumerator AttackC()//자동공격
    {
        while(true)
        {
            if (GameObject.Find("Ship"!= null)
            {
                //bullet 생성                                             
                GameObject bulletGO = new GameObject("Bullet");
                bulletGO.transform.position = bulletInitPoint.transform.position;
                Bullet bullet = bulletGO.AddComponent<Bullet>();
                var model = Instantiate(App.bulletPrefab);
                model.transform.SetParent(bulletGO.transform, false);
                model.transform.localPosition = Vector3.zero;
                target = GameObject.Find("Ship").transform.position;
                bullet.GoTo(target);//발사(비유도탄)   
            }
            yield return new WaitForSeconds(1f);
        }
    }
    // Update is called once per frame
    void Update()
    {
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        Rigidbody rigidBody = this.gameObject.AddComponent<Rigidbody>();
        boxCollider.isTrigger = true;
        boxCollider.size = new Vector3(0.07f, 0.07f, 0.2f);
        rigidBody.useGravity = false;
        rigidBody.isKinematic = true;
        this.tag = "bullet";
    }
    public void GoTo(Vector3 target)
    {        
        StartCoroutine(GoToC(target));
    }
    public void GoTo()
    {
        StartCoroutine(GoToC());
    }
    IEnumerator GoToC()
    {        
        while (true)
        {
            this.transform.position += this.transform.up * 3 * Time.deltaTime;
            if (this.transform.position.x <= -1.96f || this.transform.position.x >= 1.96f || this.transform.position.y >= 4.4f || this.transform.position.y <= -1.7f)
            {
                Destroy(this.gameObject);
            }
            
            yield return null;
        }        
    }
    IEnumerator GoToC(Vector3 target)
    {
        var vc = (target - this.transform.position).normalized;
        while(true)
        {
            this.transform.position += vc * 1 * Time.deltaTime;
            if (this.transform.position.x <= -1.96f || this.transform.position.x >= 1.96f || this.transform.position.y >= 4.4f || this.transform.position.y <= -1.7f)
            {
                Destroy(this.gameObject);
            }
            //if (Vector3.Distance(target, this.transform.position) <= 0.01f)
            //{
            //    Destroy(this.gameObject);
            //}
            yield return null;
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag != "bullet")
        {
            GameObject explosionInst = Instantiate(App.explosion);
            explosionInst.transform.position = this.gameObject.transform.position;
            Destroy(this.gameObject);
        }
        
 
        
        
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BGScroller : MonoBehaviour
{
    private MeshRenderer render;
    private float offset;
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<MeshRenderer>();
    }
 
    // Update is called once per frame
    void Update()
    {
        offset += Time.deltaTime * speed;
        render.material.mainTextureOffset = new Vector2(0, offset);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class explosion : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
    void DestroyGO()
    {
        Destroy(this.gameObject);
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

explosion 스프라이트 애니메이션 만들기:

1. 스프라이트 png파일을 받아서 slice하여 sprite로 만든다.

2. gameobject를 하나 생성하여 Sprite Renderer 컴포넌트를 추가한 후에 Sprite에 생성한 explosion sprite를 드래그한다.

3. window창 -> animation으로 들어가 2번에서 만든 gameobject 선택후 클립 생성, sprite를 드래그하여 프레임을 씌운다. 

4. 원하는 프레임을 골라 이벤트를 추가한다.

5. 스크립트를 추가해 2번에서 만든 gameobject에 추가한 후 메서드를 생성, 4번에서 만든 프레임을 선택해 실행될 메서드(스크립트에있는)를 선택한다.

6.다시 프리팹화 하여 추후에 사용한다.

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

오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.10 오브젝트 풀 활용  (0) 2019.12.10
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
ref 와 out  (0) 2019.10.31
:

12.02 객체 충돌

C#/Study 2019. 12. 2. 23:44

예제: Hero 게임 오브젝트가 특정 지역으로 이동중일때 어떤 객체와 부딪히면 문자열을 출력한다.

코드:

 

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
53
using UnityEngine;
public class App : MonoBehaviour
{
    public Button btnMoveCoroutine;
    public Button btnMoveUpdate;
    public Hero hero;
    public GameObject targetPoint;
    // Start is called before the first frame update
    void Start()
    {
        //GameObject heroGO = new GameObject("Hero");
        //hero = heroGO.AddComponent<Hero>();
 
        //string path = string.Format("Prefabs/{0}", "ch_01_01");
        //var prefab = Resources.Load<GameObject>(path);
        //var model = Instantiate(prefab);
        //model.transform.SetParent(heroGO.transform, false);
        //model.transform.localPosition = Vector3.zero;
        //hero.model = model;
 
        hero.onMove = (target) =>
        {
            var dis = Vector3.Distance(hero.transform.position, target.transform.position);
            var vc = target.transform.position - hero.transform.position;
            var dir = vc.normalized;
            var speed = 1;
            hero.transform.position += dir * speed * Time.deltaTime;
            if (dis <= 0.5f)
            {
                hero.transform.position = target.transform.position;
                hero.model.GetComponent<Animation>().Play("idle@loop");
                hero.isMove = false;
            }
        };
 
        btnMoveCoroutine.onClick.AddListener(() =>
        {
            hero.Move2(targetPoint);
        });
        btnMoveUpdate.onClick.AddListener(() => {
            hero.Move(targetPoint);
        });
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Hero : MonoBehaviour
{
    public bool isMove;
    public Action<GameObject> onMove;
    public GameObject target;
    public GameObject model;
    IEnumerator onMoveCoroutine;
    // Start is called before the first frame update
    void Start()
    {
        onMoveCoroutine = OnMoveCoroutine();
    }
 
    public void Move(GameObject target)
    {
        this.target = target;
        isMove = true;
    }
    public void Move2(GameObject target)
    {
 
        this.target = target;
        //isMove = true;
        this.model.GetComponent<Animation>().Play("run@loop");
        StartCoroutine(onMoveCoroutine);
    }
    public void Update()
    {
        if (this.isMove == true)
        {
            this.model.GetComponent<Animation>().Play("run@loop");
            this.onMove(target);
        }        
        if (this.transform.position == target?.transform.position)
        {
            StopCoroutine(onMoveCoroutine);
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "Player")
        {
            Debug.Log("부딫혔습니다.");
        }
    }
 
    IEnumerator OnMoveCoroutine()
    {
        while (true)
        {
            var dis = Vector3.Distance(this.transform.position, target.transform.position);
            var vc = target.transform.position - this.transform.position;
            var dir = vc.normalized;
            var speed = 1;
            this.transform.position += dir * speed * 0.01f;
            this.transform.LookAt(target.transform);
            if (dis <= 0.1f)
            {
                this.model.GetComponent<Animation>().Play("idle@loop");
                this.transform.position = target.transform.position;
                //isMove = false;
            }
            yield return new WaitForSeconds(0.01f);
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

코드뿐만 아니라 유니티에서 Hero 게임오브젝트와 collider 오브젝트에 각각 Box Collider, Rigid Body 컴포넌트를 부착하고 is Trigger와 is Kinematic 항목에 체크표시를 해주었다.

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

12.10 오브젝트 풀 활용  (0) 2019.12.10
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
struct 와 클래스의 차이  (0) 2019.11.02
ref 와 out  (0) 2019.10.31
초기화  (0) 2019.10.31
:

struct 와 클래스의 차이

C#/Study 2019. 11. 2. 02:36

class 는 참조 형식이고 struct는 값형식이다.

코드:

 

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
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Project
{
    class App
    {
        public App()
        {
            classData a = new classData();
            a.str = "홍길동";
            classData b = a;            
            b.str = "이호준";
 
            structedData structedData;
            structedData.str = "홍길동";
            structedData structedData2 = structedData;
 
            structedData2.str = "이호준";
            Console.WriteLine(structedData.str);
            Console.WriteLine(a.str);
 
        }
        
    }
    struct structedData
    {
        public string str;
    }
    class classData
    {
        public string str;
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

출력:

첫째 줄에는 값형식인 structedData.str 의 값이 다른 객체가 참조하는게 아니기 때문에 다른 객체에서 값을 바꿔도 structedData.str 의 값은 바뀌지 않는것이 확인 되었다.

둘째 줄에는 참조 형식인 a의 값을 다른 객체가 참조하기 때문에 다른객체에서 값을 바꾸면 a의 참조값도 바뀌게 되는것이 확인 되었다.

또한 class는 파생클래스를 가지고 파생이 될 수 있는 반면 struct는 인터페이스로부터만 파생이 가능하다.

예시:

 

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

12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
ref 와 out  (0) 2019.10.31
초기화  (0) 2019.10.31
박싱과 언박싱  (0) 2019.10.31
:

ref 와 out

C#/Study 2019. 10. 31. 01:11
ref를 이용하면 매개변수가 인수로부터 받은 값이 초기화가 되어있다는 가정하에 그 값을 사용하게된다. 그래서 그 값이 초기화가 되어있지않으면 컴파일 에러가 발생한다.

out을 이용하면 매개변수가 인수로부터 받은 값을 메소드를 실행하면서 초기화를 하기로 약속이 되어있기때문에 굳이 초기화를 할 필요가 없는것이다.

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

12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
초기화  (0) 2019.10.31
박싱과 언박싱  (0) 2019.10.31
배열 내 요소중 최대값 구하기  (0) 2019.10.15
:

초기화

C#/Study 2019. 10. 31. 00:59
초기화
데이터를 변수(공간)에 집어넣는 과정을 초기화라고 합니다.
Ex) int x = 10;
→ 이는 변수 선언과 초기화를 동시에 해준 것입니다.

 변수를 처음 만들게 되면 기존 메모리에 들어있는 값을 그대로 사용하게 되기 때문에 어떤 값이 들어있는지 알 수 없습니다. 그래서 예외 발생의 가능성이 있죠. 따라서 프로그램이 변수에 들어있는 값을 예상할 수 있는 범위 이내에 두게 하기 위해 초기화를 진행합니다.

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

struct 와 클래스의 차이  (0) 2019.11.02
ref 와 out  (0) 2019.10.31
박싱과 언박싱  (0) 2019.10.31
배열 내 요소중 최대값 구하기  (0) 2019.10.15
성적표만들기  (0) 2019.09.27
: