1. 설정(태그 방식으로 안해도 됨 hierarchy name명으로 해도 됨.)
2. 오브젝트 설정
메인 오브젝트
작은 오브젝트
3. C#코드 test와 SmallCube
| 
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 | 
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
public class test : MonoBehaviour { 
    int countSmallCube; 
    private void Start() 
    { 
        countSmallCube = 0; 
    } 
    private void OnTriggerEnter(Collider col) 
    { 
        if (col.tag == "SmallCube") 
        { 
            countSmallCube++; 
            // 1번째만 메인 오브젝트를 따라가고 다음부터 작은 오브젝트만 따라가게 string 타켓네임을 바꾼다. 
            if (countSmallCube > 1) col.GetComponent<SmallCube>()._targetName = "SmallCube" + (countSmallCube - 1).ToString(); 
            // 오브젝트의 태그명을 바꿈 
            col.gameObject.tag = "SmallCube" + countSmallCube.ToString(); 
            col.GetComponent<SmallCube>().TargetFind(); 
            col.GetComponent<SmallCube>()._touch = true; 
        } 
    } 
} | cs | 
| 
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; 
public class SmallCube : MonoBehaviour { 
    public string _targetName = "Cube"; 
    Transform _target; 
    public bool _touch = false; 
    private float dampSpeed = 3;  // 따라가는 속도 
    // Update is called once per frame 
    void Update () { 
        if (_touch == true) FollowTarget(); 
    } 
    public void TargetFind() 
    { 
        // 타겟 string을 바꿈 
        _target = GameObject.FindGameObjectWithTag(_targetName).GetComponent<Transform>(); 
    } 
    void FollowTarget() 
    { 
        // Gets a vector that points from the player's position to the target's. 
        var heading = _target.position - this.transform.position; 
        // 거리가 멀어지면 실행 
        if (heading.sqrMagnitude > 1) 
        { 
            // Target is within range. 
            transform.position = Vector3.Lerp(transform.position, _target.position, Time.deltaTime * dampSpeed); 
        } 
        // 방향을 봄 
        transform.LookAt(_target); 
    } 
} | cs | 





댓글
댓글 쓰기