sena
sena

Reputation: 13

How can I add objects to a scene via button click in Unity?

I would like to know how to use a button click to bring objects to the scene.

Upvotes: 1

Views: 10014

Answers (2)

I think use gameObject z postion value and show or hide when this object allready created

Find current gameObject and set transform.postion.z = -1 or 1

if gameObject z postion set to -1 hideObject else showObject

sampleCode

 float yourChose = -1f; // chose object hide or show (-1 or 1 )

 foreach (var item in  FindObjectsOfType(typeof(GameObject)) as GameObject[])
            {                               
                if (item != null && item.name == "CurrentObjectName")
                {
                    item.transform.position = new Vector3(item.transform.position.x, item.transform.position.y, yourChose); 
                }
            } 

Upvotes: 0

1) Create a button using Unity GUI system.

2) Create a script:

public GameObject sampleObject;

public void AddObject()
{
    Instantiate(sampleObject, Vector3.zero, Quaternion.Identity);
}

3) Attach this script to an object in the scene, and set a prefab to sampleObject.

4) Select your button and in the Inspector add a new OnClick script, and select the object with the new script attached, select AddObject() method.

Now when you click on the button it should instantiate an object at (0.0f, 0.0f, 0.0f).

Hope that helps you.

Upvotes: 4

Related Questions