[Unity] Prefab을 코드로 씬에 불러오기

Yerin·2023년 7월 11일
0

PrefabTest.cs

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrefabTest : MonoBehaviour
{
    public GameObject prefab;
    
    void Start()
    {

        Instantiate(prefab);
    }

   
}

속성 창에서 적용할 Prefab을 끌어와주면 끝!

실행을 하면 뿅! 하고 생긴다.

삭제하고 싶다면?

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrefabTest : MonoBehaviour
{
    public GameObject prefab;

    GameObject tank;
    void Start()
    {

        tank = Instantiate(prefab);

		//3초 후에 사라지도록 함
        Destroy(tank, 3.0f);
    }

   
}

속성창에서 prefab을 지정하지 않아도 되는 방법

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrefabTest : MonoBehaviour
{
    GameObject prefab;
    GameObject tank;
    void Start()
    {
        prefab = Resources.Load<GameObject>("Prefabs/Tank");
        tank = Instantiate(prefab);

        Destroy(tank, 3.0f);
    } 
}
profile
재밌는 코딩 공부

0개의 댓글