0

I have a task that I am supposed to create a web based client that allows users to create objects (in my case, furniture) and move them around and so on.

For this, I have created a button. When the button is pressed, I want to create an object, for example, a chair. For educational purposes, a cube works equally well.

The code I have to accomplish this is as following:

    function OnGUI() {

        if(GUI.Button(Rect(Screen.width - 170, Screen.height - Screen.height * 0.98,150,30), string)){

            GUI.Button(Rect(50,50,150,30), "test");

        }
    }

Here, I tried to create a new button, but the goal is to create an object of some sort.

I do not know how to proceed, and I have very little experience in Javascript.

Regards

1 Answer 1

1

Considering you are running based on Unity Documentation for creating objects the correct function need to be called is Instantiate. to do that you need to have a reference of an object you want to create. Example:

    // Instantiates 10 copies of prefab each 2 units apart from each other
var prefab : Transform;//From the inspector drag and drop a prefab object(of any type) on the prefab slot
function Start ()
   {
       for (var i : int = 0;i < 10; i++) 
       {
           Instantiate (prefab, Vector3(i * 2.0, 0, 0), Quaternion.identity);
       }
   }

According to this, your code could be modified as follows:

var prefab : Transform;//From the inspector drag and drop a prefab object(of any type) 
  function OnGUI() {

        if(GUI.Button(Rect(Screen.width - 170, Screen.height - Screen.height * 0.98,150,30), string))
        {
             var aPosition = Vector3(1, 1, 1);//Sets the position in the 3d space we are gonna position the prefab
             Instantiate (prefab, aPosition, Quaternion.identity);

        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

That seemed to work just fine. However, if I want to create a new button (like a menu) when the button is clicked, the instantiate function does not work. Any ideas on how I could achieve that? That is, when the button is pressed, a selectionGrid of buttons is shown...
The problem here is that the Instantiate function cannot be used to create GUI.Elements, it requires an object as a parameter. According to your code, as long as you press the first GUI.Button another button of name test will be spawned

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.