- Home /
How to Update Variable from GUI
I'm using the GUI to make a Turn Based Combat System with buttons. I'm having problems getting the 'void OnGUI' to update a variable outside of the GUI and keep it when a button is clicked. My goal is to have the object move to the enemy and move back to position. Here is a stripped down version of my code. I'm still new to coding any help will be appreciate.
using UnityEngine;
using System.Collections;
public class Menu : MonoBehaviour
{
private string[] selStrings = { "Attacks", "Magic" };
enemyObject EObject = new enemyObject();
void OnGUI()
{
if(player.hitPoints > 0 && enemy.hitPoints > 0)
{
selGridInt = GUI.SelectionGrid(new Rect(0, Screen.height - 55, 160, 47), selGridInt, selStrings, 2);
if(turn == 1)
if(selGridInt == 0)
if (GUI.Button (new Rect (255, Screen.height - 48, 100, 40), "Punch"))
{
punch(player, enemy);
EObject.wantingToMove(2);
turn -= 1;
}
}
}
}
public class enemyObject : MonoBehaviour
{
public int run;
void Update ()
{
if(run == 2)
transform.Translate(new Vector3(0,0,1) * Time.deltaTime);
}
public int wantingToMove(int a)
{
run = a;
return run;
}
}
I formatted your code for you using the 101/010 button, but your incorrect indenting and extra lines still makes this code difficult to read. Cleaning it up will get you a better response.
Did you try to make the enemyObject public? I think the problem is that it is available in the OnGUI, but void Update() can not see it.
Answer by robertbu · Oct 03, 2013 at 03:40 PM
'enemyObject' is derived from MonoBehaviour, which means that this script should be attached to a game object and exist as a 'component' of that game object. With these kinds of classes, you don't use 'new' to create them as you've done on line 8. You need to first find the game object this script is attached to, then you need to find the component.
http://docs-jp.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
http://docs-jp.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Components.html
Your answer
Follow this Question
Related Questions
How can I Include string variables in Rich Text? 1 Answer
variable before (dot) 2 Answers
Optimizing OnGUI 1 Answer
Limiting digits in GUI displayed variables (or "snap to" GUI slider). 1 Answer
Input player name to a variable 2 Answers