Add gameobject dynamically to scene in Unity3d

Ashwani K picture Ashwani K · Mar 19, 2013 · Viewed 58.3k times · Source

I am creating a scene in which I want to show list of offers. In order to show the offer, I created a prefab with placeholders for the offer details which I will get at runtime. I created a place holder in the scene to add the prefab to the scene, but it is not showing on the UI. OfferHolderClass:

using UnityEngine;
using System.Collections;

public class OfferHolder : MonoBehaviour {

    public GameObject localOffer;
    // Use this for initialization
    void Start () {
        GameObject offer = Instantiate(localOffer) as GameObject;
        offer.GetComponent<Offer>().Text = "Testing";
        offer.transform.parent = this.transform;
    }

    // Update is called once per frame
    void Update () {

    }
}

I am new to Unity and am not sure what I am missing here.

Answer

UnityFan2013 picture UnityFan2013 · Oct 15, 2013
//Drag object prefab to variable in inspector
public GameObject spawnObject;
//----------------------------------------

Below will create GameObject using the objects Own Transform settings.

 GameObject clone;
    clone = Instantiate(spawnObject.transform, 
                        spawnObject.transform.position, 
                        spawnObject.transform.rotation) as GameObject;

Below will create GameObject using the objects Parents Transform settings.

 GameObject clone;
    clone = Instantiate(spawnObject.transform, 
                        transform.position, 
                        transform.rotation) as GameObject;

Not sure if this helps, but good luck on your game :)