parent%26SetParent - TeamCrazyPerformance/Game_study GitHub Wiki

parent&SetParent

  • parent와 SetParent 둘 다 부모를 지정해주는 키워드와 함수이다.
  • 프리팹 인스터스 생성 시 Hierachy(계층창)에 생성되는 것을 정리해준다.
  • 혹은 부모관계가 아닌 것을 오브젝트를 이어준다.
  • parent은 해당 부모를 (get, set) 가능
  • SetParent은 직접 부모를 set함

예시

  • space바 클릭 시 무기 발사
  • image
  • Durid 프리팹
  • image
  • 무기 프리팹
  • image

Durid.cs


public class Druid : MonoBehaviour
{
    public GameObject weapon;
    public float projectileSpeed = 10f;
    public float fireRate = 0.5f;
    public Knife knife;

    private float nextFireTime = 0f;
    void Update()
    {
        if (Input.GetKey(KeyCode.Space) && Time.time > nextFireTime)
        {
            nextFireTime = Time.time + fireRate;
            GameObject obj = Instantiate(weapon, transform.position, Quaternion.identity);
            obj.transform.parent = transform;
            Rigidbody2D rb = obj.GetComponent();
            rb.velocity = new Vector2(projectileSpeed, 0f);
            Destroy(obj, 10);
            //knife.Spawn(weapon, projectileSpeed, transform);
        }
    }
}

Knife.cs


public class Knife : MonoBehaviour
{
    public void Spawn(GameObject weapon, float speed, Transform character)
    {
        GameObject obj = Instantiate(weapon, character.position, Quaternion.identity);
        //obj.transform.SetParent(character);
        //obj.transform.parent = GameObject.Find("Durid").transform;
        Rigidbody2D rb = obj.GetComponent();
        rb.velocity = new Vector2(speed, 0f);
        Destroy(obj, 10);
    }
}


19오성혁

⚠️ **GitHub.com Fallback** ⚠️