- Home /
changing a variable with a gui button
Hi All
Ok so I'm going to get right into it. I was wondering how to change a variable( game object) with a GUI button? The variable will be in the same script but let me explain what I am trying to accomplish.
I am making a object selection grid out of gui so that when you click on a button then it will change the variable to the object associated with a gui button ? If that makes sense ??
I want to have 4 different buttons in 1 script. When you press the food button then it will change the variable to food and instantiate the food gameobject but when you click on the wood button then it will change that same variable to wood so it will instantiate wood instead of food ? Is this possible ??
Answer by ByteSheep · Mar 16, 2012 at 09:04 PM
If all your buttons are in the same script and I understand the question correctly, you could use something as simple as this to switch between instantiating food and wood:
var InstantiateVar : int = 0;
var FoodPrefab : Transform;
var WoodPrefab : Transform;
function Update() {
if(GUI.Button(Rect(10,70,50,30),"Food"))
{
InstantiateVar = 0;
}
if(GUI.Button(Rect(100,170,50,30),"Wood"))
{
InstantiateVar = 1;
}
if(GUI.Button(Rect(190,270,50,30),"Instantiate"))
{
if(InstantiateVar == 0)
{
Instantiate(FoodPrefab, transform.position, transform.rotation);
}
if(InstantiateVar == 1)
{
Instantiate(WoodPrefab, transform.position, transform.rotation);
}
}
}
Let me know if I misinterpreted your question :) Sounds like you are trying to change a variable when the user clicks on different buttons
Your answer
![](https://koobas.hobune.stream/wayback/20220613065211im_/https://answers.unity.com/themes/thub/images/avi.jpg)