Script being autorun on start instead of button click.
I am trying to have a script run when a button is clicked, but it just automatically runs when play is pressed in the editor. I have the script attached to an empty game object and the added onto the Button (Script) component under "On Click ()." This is the script:
using UnityEngine;
using System.Collections;
public class ButtonPress : MonoBehaviour {
int number;
void Start() {
number = Random.Range(1,1000);
}
void OnGUI() {
Rect oRectangle = new Rect(10, 10, 200, 200);
GUI.Label(oRectangle,"The number that was generated: " + number);
}
}
Any help would be greatly appreciated (I am a serious noob)!
Answer by MadDevil · Oct 07, 2015 at 04:27 AM
Start, will be called every time you press the play in editor.
http://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
so instead call a function on the button press.
void RandomGenerator() { number = Random.Range(1, 1000); }
Answer by itsharshdeep · Oct 07, 2015 at 04:31 AM
Hi @Klaster55
First of all the script you above wrote contains the 'OnGUI' method which run with every frame (same as Update works)
So if the script is enable it will run automatically without your permission.
Now suppose you want to print the random Number when you click on Button, Then just do the following steps :-
int randomNum;
public void CreateRandomNumber() {
randomNum = Random.Range (0,100);
print("The number that was generated: " + randomNum);
}
Now pass this method in 'OnClick()' property it will print a log in console.
If this answer is not appropriate to your question then please try to describe with little more description in comment. Thanks