OnGui won't show up when I start the game for some reason. I've attached the script to a gameobject:
public class username : MonoBehaviour {
private static string user = "";
void OnGui()
{
GUI.Label(new Rect((Screen.width / 2), (Screen.height / 2), 300, 300), "Username");
user = GUI.TextField(new Rect(-4, 0, 100, 100), user);
if (GUI.Button(new Rect(-4, 0, 200, 30), "Continue"))
{
WWWForm form = new WWWForm();
form.AddField("", user);
WWW w = new WWW("http://site/register.php", form);
StartCoroutine(register(w));
}
}
Thanks
OnGui() is case-sensitive and needs to be OnGUI().
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnGUI.html
Related
I'm trying to archive two things :
To be able to change for each individual button he own color in the inspector in runtime.
To make a color switch for example when clicking the "LOOP" button change the button color from his current color to another color like a switch between current color and blue. so i know that is loop is true or if loop pressed once make it blue if pressed again switch back to the original color/another color.
This is how the buttons looks like before using the GUI.backgroundColor in the original :
Before using the GUI.backgroundColor in the script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUIExamples : MonoBehaviour
{
public Texture btnTexture;
public Color color;
private void OnGUI()
{
if (!btnTexture)
{
Debug.LogError("Please assign a texture on the inspector");
return;
}
GUI.backgroundColor = color;
if (GUI.Button(new Rect(10, 10, 170, 30), "LOOP"))
Debug.Log("Clicked the button with an image");
GUI.backgroundColor = color;
if (GUI.Button(new Rect(10, 50, 170, 30), "CHANGE DIRECTION"))
Debug.Log("Clicked the button with text");
GUI.backgroundColor = color;
if (GUI.Button(new Rect(10, 90, 170, 30), "PING PONG"))
Debug.Log("Clicked the button with text");
GUI.backgroundColor = color;
if (GUI.Button(new Rect(10, 130, 170, 30), "STOP"))
Debug.Log("Clicked the button with text");
GUI.backgroundColor = color;
if (GUI.Button(new Rect(10, 170, 170, 30), "PAUSE"))
Debug.Log("Clicked the button with text");
}
}
Update :
This is what i tried but when i'm changing the color in the inspector in runtime it's not changing the box color :
It will change the color only if i set the color at this line like this :
currentStyle.normal.background = MakeTex( 2, 2, new Color( 0f, 1f, 0f, 0.5f ) );
But i want to change the color in runtime in real time in the inspector using the color variable.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUIExamples : MonoBehaviour
{
public Texture btnTexture;
public Color color;
private GUIStyle currentStyle = null;
private Color oldColor;
private void Start()
{
oldColor = color;
}
private void OnGUI()
{
if (!btnTexture)
{
Debug.LogError("Please assign a texture on the inspector");
return;
}
if (GUI.Button(new Rect(10, 10, 170, 30), "LOOP"))
Debug.Log("Clicked the button with an image");
if (GUI.Button(new Rect(10, 50, 170, 30), "CHANGE DIRECTION"))
Debug.Log("Clicked the button with text");
if (GUI.Button(new Rect(10, 90, 170, 30), "PING PONG"))
Debug.Log("Clicked the button with text");
if (GUI.Button(new Rect(10, 130, 170, 30), "STOP"))
Debug.Log("Clicked the button with text");
InitStyles();
GUI.Box(new Rect(10, 170, 170, 30), "PAUSE", currentStyle);
if (GUI.Button(new Rect(10, 170, 170, 30), "PAUSE"))
Debug.Log("Clicked the button with text");
}
private void InitStyles()
{
if(oldColor != color)
{
currentStyle = null;
}
if (currentStyle == null)
{
currentStyle = new GUIStyle(GUI.skin.box);
currentStyle.normal.background = MakeTex(2, 2, new Color(color.r, color.g, color.b, color.a));
oldColor = color;
}
}
private Texture2D MakeTex(int width, int height, Color col)
{
Color[] pix = new Color[width * height];
for (int i = 0; i < pix.Length; ++i)
{
pix[i] = col;
}
Texture2D result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}
}
I wanted to create a quick "main menu" scene for my Google Tango project using Unity.This is the code I got:
using UnityEngine;
using System.Collections;
public class Main : MonoBehaviour {
public Object[] scenes;
void OnGUI () {
if (GUI.Button(new Rect(100, 200, 200, 100), "test Button")){}
for (int i = 0; i < scenes.Length; i++) {
if(GUI.Button(new Rect(0, i * Screen.height / scenes.Length, Screen.width, Screen.height / scenes.Length), "Load " + scenes[i].name)){
Application.LoadLevel(scenes[i].name);
}
}
}
}
This should (and does.. at least in the Editor) work just fine.However I can only see the single "test Button" on screen.
Why does this happen?
I am making an application for my game that stores all the user activity and other variables in a .txt file. I wrote the part to get the parameter and also the part to make a text file to write something down.
But I cant get to link these 2 parts.
I will post the code here, notice that I have int and string parameters who need to get written down.
using UnityEngine;
using System.Collections;
using System.IO;`
public class Levels_Menu : MonoBehaviour
{
public GUISkin skin;
void OnGUI()
{
GUI.skin = skin;
if (GUI.Button(new Rect(Screen.width / 2 - 750, Screen.height / 2 - 100, 300, 100), "EASY"))
{
//Application.LoadLevel("Game_Difficulty_Easy");
ApplicationLoadLevel("Game_Difficulty_Easy");
}
if (GUI.Button(new Rect(Screen.width / 2 - 450, Screen.height / 2 - 100, 300, 100), "NORMAL"))
{
//Application.LoadLevel("Game_Difficulty_Normal");
ApplicationLoadLevel("Game_Difficulty_Normal");
}
if (GUI.Button(new Rect(Screen.width / 2 - 150, Screen.height / 2 - 100, 300, 100), "HARD"))
{
//Application.LoadLevel("Game_Difficulty_Hard");
ApplicationLoadLevel("Game_Difficulty_Hard");
}
if (GUI.Button(new Rect(Screen.width / 2 + 150, Screen.height / 2 - 100, 300, 100), "SURVIVAL"))
{
//Application.LoadLevel("Game_Difficulty_Survival");
ApplicationLoadLevel("Game_Difficulty_Survival");
}
if (GUI.Button(new Rect(Screen.width / 2 + 450, Screen.height / 2 - 100, 300, 100), "FIND THE COLOR"))
{
//Application.LoadLevel("Game_Difficulty_FindTheColor");
ApplicationLoadLevel("Game_Difficulty_FindTheColor");
}
if (GUI.Button(new Rect(Screen.width / 2 - 250, Screen.height / 2 - 300, 500, 100), "PLAY RANDOM LEVEL"))
{
//Application.LoadLevel(Random.Range(4, 8));
ApplicationLoadLevel(Random.Range(4, 8));
}
if (GUI.Button(new Rect(Screen.width / 2 + 400, Screen.height / 2 - 300, 300, 100), "MAIN MENU"))
{
//Application.LoadLevel("Main_Menu");
ApplicationLoadLevel("Main_Menu");
}
}
private void ApplicationLoadLevel(string level)
{
Logger.LogThis(level);
Application.LoadLevel(level);
}
private void ApplicationLoadLevel(int level)
{
Logger.LogThis(level);
Application.LoadLevel(level);
}
public static class Logger
{
public static void LogThis()
{
string path = #"C:\temp\ExampleNew.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine();
tw.Close();
}
else if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine();
tw.Close();
}
}
}
}
The answer appears simply: rewrite public static void LogThis() as public static void LogThis(string text) and then, when you write to the text file, use tw.WriteLine(text)
Granted, this doesn't support directly writing the int, so you can either
use the ToString() method on the int when passing it as a parameter or
change the method signature to public static void LogThis(object toWrite).
Finally, I would suggest refactoring your LogThis method to the following:
public static void LogThis(object toWrite)
{
string path = #"C:\temp\ExampleNew.txt";
if (!File.Exists(path))
{
File.Create(path);
}
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine(toWrite);
tw.WriteLine();
tw.Close();
}
UPDATE: TextWriter implements IDisposable! Yahoo! Use a using statement to ensure the stream is closed and released:
public static void LogThis(object toWrite)
{
string path = #"C:\temp\ExampleNew.txt";
if (!File.Exists(path))
{
File.Create(path);
}
using (TextWriter tw = new StreamWriter(path, true))
{
tw.WriteLine(toWrite);
tw.WriteLine();
}
}
Error saying 'MPPlayer' could not be found, however I think it's referenced.
private void Menu_Lobby()
{
ScrollLobby = GUILayout.BeginScrollView(ScrollLobby, GUILayout.MaxWidth("200"));
foreach (MPPlayer pl in MultiplayerManager.instance.PlayerList)
{
GUILayout.Box (pl.PlayerName);
}
GUILayout.EndScrollView();
}
Full page code:
using UnityEngine;
using System.Collections;
public class MenuManager : MonoBehaviour
{
public string CurrentMenu;
public string MatchName = "";
public string MatchPassword = "";
public int MatchMaxPlayers = 20;
private Vector2 ScrollLobby = Vector2.zero;
void Start()
{
CurrentMenu = "Main";
MatchName = "My Server " + Random.Range(0 , 100);
}
void OnGUI()
{
if (CurrentMenu == "Main")
Menu_Main();
if (CurrentMenu == "Lobby")
Menu_Lobby();
if (CurrentMenu == "Host")
Menu_HostGame();
}
public void NavigateTo(string nextmenu)
{
CurrentMenu = nextmenu;
}
private void Menu_Main()
{
if (GUI.Button(new Rect(10,10,200,50), "Create Game"))
{
NavigateTo ("Host");
}
GUI.Label(new Rect(220, 10, 130, 30), "Player Name");
MultiplayerManager.instance.PlayerName = GUI.TextField( new Rect(350, 10, 150, 30), MultiplayerManager.instance.PlayerName);
if (GUI.Button (new Rect(510,10,100,30), "Save"))
{
PlayerPrefs.SetString("PlayerName", MultiplayerManager.instance.PlayerName);
}
}
private void Menu_HostGame()
{
// Buttons Host Game
if (GUI.Button(new Rect(10,10,200,50), "Back"))
{
NavigateTo("Main");
}
if (GUI.Button(new Rect(10,60,200,50), "Start Server"))
{
MultiplayerManager.instance.StartServer(MatchName, MatchPassword, MatchMaxPlayers);
}
GUI.Label(new Rect(220, 10, 130, 30), "Match Name");
MatchName = GUI.TextField( new Rect(400, 10, 200, 30), MatchName);
GUI.Label(new Rect(220, 50, 130, 30), "Match Password");
MatchPassword = GUI.PasswordField( new Rect(400, 50, 200, 30), MatchPassword, '*');
GUI.Label(new Rect(220, 90, 130, 30), "Match Max Players");
GUI.Label(new Rect(400, 90, 200, 30), MatchMaxPlayers.ToString());
MatchMaxPlayers = Mathf.Clamp (MatchMaxPlayers, 6, 20); // Allows min of 6 players and a max of 20 players.
if (GUI.Button (new Rect(425,90,25,30), "+"))
MatchMaxPlayers += 2; // Adds 2 players to the number
if (GUI.Button (new Rect(450,90,25,30), "-"))
MatchMaxPlayers -= 2; // Takes 2 players from the number
}
private void Menu_Lobby()
{
ScrollLobby = GUILayout.BeginScrollView(ScrollLobby, GUILayout.MaxWidth("200"));
foreach (MPPlayer pl in MultiplayerManager.instance.PlayerList)
{
GUILayout.Box (pl.PlayerName);
}
GUILayout.EndScrollView();
}
void OnServerInitialized()
{
NavigateTo("Lobby");
}
void OnConnectedToServer()
{
NavigateTo("Lobby");
}
}
maybe this would help
http://unity3d.com/learn/tutorials/modules
especially this one
http://unity3d.com/learn/tutorials/modules/beginner/scripting/variable-scope-and-access-modifiers
Change foreach (MPPlayer pl in MultiplayerManager.instance.PlayerList) to foreach (var pl in MultiplayerManager.instance.PlayerList) and mouseover in VS the var part to find out what's the actual type name.
I was wondering how to approach creating a HUD.
I currently have health, mana, and experience bar drawn to the screen at set coordinates. Downside of this is that when the camera pans the bars stay at their set coordinates, I want them to adjust to the viewport or not be influenced by positions but just simply drawn to the screen.
Edit
I managed to get the HUD to adjust using the camera's x and y coordinates.
I've created a separate class for drawing the HUD, but now they don't adjust.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using GameOne.Components;
namespace GameOne.GameScreens
{
public class HUD : BaseGameState
{
Player player;
Texture2D HealthBar;
Texture2D HealthBarPositive;
Texture2D HealthBarNegative;
Texture2D ManaBar;
Texture2D ManaBarPositive;
Texture2D ManaBarNegative;
Texture2D ExpBar;
Texture2D ExpBarPositive;
int CurrentHealth = 100;
int CurrentMana = 45;
int CurrentExp = 0;
public HUD(Game game, GameStateManager manager)
: base(game, manager)
{
player = new Player(game);
}
public void LoadContent()
{
base.LoadContent();
HealthBar = Game.Content.Load<Texture2D>(#"GUI\healthBar");
HealthBarPositive = Game.Content.Load<Texture2D>(#"GUI\healthBarPositive");
HealthBarNegative = Game.Content.Load<Texture2D>(#"GUI\healthBarNegative");
ManaBar = Game.Content.Load<Texture2D>(#"GUI\manaBar");
ManaBarPositive = Game.Content.Load<Texture2D>(#"GUI\manaBarPositive");
ManaBarNegative = Game.Content.Load<Texture2D>(#"GUI\manaBarNegative");
ExpBar = Game.Content.Load<Texture2D>(#"GUI\expBar");
ExpBarPositive = Game.Content.Load<Texture2D>(#"GUI\expBarPositive");
}
public void Update(GameTime gameTime)
{
if (InputHandler.KeyDown(Keys.F1))
{
CurrentHealth += 1;
}
if (InputHandler.KeyDown(Keys.F2))
{
CurrentHealth -= 1;
}
if (InputHandler.KeyDown(Keys.F3))
{
CurrentMana += 1;
}
if (InputHandler.KeyDown(Keys.F4))
{
CurrentMana -= 1;
}
if (InputHandler.KeyDown(Keys.F5))
{
CurrentExp += 1;
}
if (InputHandler.KeyDown(Keys.F6))
{
CurrentExp -= 1;
}
CurrentHealth = (int)MathHelper.Clamp(CurrentHealth, 0, 100);
CurrentMana = (int)MathHelper.Clamp(CurrentMana, 0, 45);
CurrentExp = (int)MathHelper.Clamp(CurrentExp, 0, 500);
}
public void Draw(GameTime gameTime)
{
GameRef.SpriteBatch.Draw(
HealthBarNegative,
new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150, 15),
Color.White);
GameRef.SpriteBatch.Draw(
HealthBarPositive,
new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150 * (int)CurrentHealth / 100, 15),
Color.White);
GameRef.SpriteBatch.Draw(
HealthBar,
new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150, 15),
Color.White);
GameRef.SpriteBatch.Draw(
ManaBarNegative,
new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 650, 150, 15),
Color.White);
GameRef.SpriteBatch.Draw(
ManaBarPositive,
new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 650, 150 * (int)CurrentMana / 45, 15),
Color.White);
GameRef.SpriteBatch.Draw(
ManaBar,
new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 650, 150, 15),
Color.White);
GameRef.SpriteBatch.Draw(
ExpBarPositive,
new Rectangle((int)player.Camera.Position.X + 10, (int)player.Camera.Position.Y + 680, 1260 * (int)CurrentExp / 500, 15),
Color.White);
GameRef.SpriteBatch.Draw(
ExpBar,
new Rectangle((int)player.Camera.Position.X + 10, (int)player.Camera.Position.Y + 680, 1260, 15),
Color.White);
}
}
}
When you are drawing your Health bars, is it inside a Spritebatch.Begin( ... ) where you specify your camera matrix?
If you draw it in its own Spritebatch.Begin, without the camera, the position of the health bars will stay relative to the screen.
When you extend you class with DrawableGameComponent, you can use the property DrawOrder to set it topmost.
The class will be a bit different, you have to overload Update, draw and LoadContent, but it will be all the same.
This is only usefull if you use a HUD with SpriteBatch.