c# 강의/유니티

20200507 - 오브젝트 생성 및 부모설정(Instantiate)

쪼혀 2020. 5. 8. 09:29

> 오브젝트,스크립트 설정

 

 


> App.cs

더보기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class App : MonoBehaviour
{
    public Hero hero;
    public GameObject[] arrHeroModels;
    public string modelName;

    // Start is called before the first frame update
    void Start()
    {
      //  this.modelName = "";
        Debug.Log(this.modelName.ToString());

        this.hero.Init(this.CreateModel(this.modelName));
    }

    private GameObject CreateModel(string modelName)
    {
        GameObject foundModel = null;
        foreach (GameObject model in this.arrHeroModels)
        {
            if (model.name == modelName)
            {
                foundModel = model;
                break;
            }
        }
        Debug.LogFormat("model: {0}", foundModel);

        //게임오브젝트를 생성함 
        var newModel = UnityEngine.Object.Instantiate(foundModel);
        return newModel;
    }
}

 

> Hero.cs

더보기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hero : MonoBehaviour
{
    public GameObject hero;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    public void Init(GameObject newModel)
    {
        //newModel.transform.SetParent(this.transform);
        newModel.transform.SetParent(this.transform, false);
        Debug.Log("zzzz"); 
    }
    
}