Unity GUI Text won't work - user-interface

I have the following problem, and I'd appreciate greatly if someone could help.
I've been trying create a roll-a-ball game in Unity, similar as the one presented in one of the tutorials on their official website, but with one difference: I'd like to add GUI text that would show the score. Every time the ball hits (and destroys) one of the rotating cubes, the score should increase by 1, and the text should show the current score.
I've watched the following tutorial:
http://unity3d.com/learn/tutorials/projects/space-shooter/counting-points
I have created the UI text, called ScoreText, and, on the other hand, I have written the script that makes an instance of GUIText class, called guitext, show the current score. However, I cannot connect my particular GUI text (ScoreText) with the script, i.e. I cannot tell the script to use that particular GUI text to show score. In the video, at 16:35, they just drag the GUI text to the instance of the GUIText class from the script (in my case, guitext), in order to tell the script it's that particular text that should show the score. But when I try to drag it, I simply can't do it. I have no idea why.
I don't know if this could cause the problem: under "Create" in the free version of Unity, I could not find anything called "GUI text" but instead I created a UI text. I know it's the same thing, but... In the script, I define an instance of GUIText class - guitext - so maybe, when I try to add my UI text to it, it won't work because my text really doesn't belong to the GUIText class?

Since you are using Unity 4.6 which has a new GUI system and not the Legacy UI which was present when the tutorial which you mentioned was made. There are two options - either you create an empty gameobject and add add a GUIText component to it. You can add the GUIText to empty gameobject by selecting it in the Hierarchy which should display the objects properties in the Inspector panel.
In the Inspector, you should see an Add Component button, click on it and search for GUIText. Add it and that should solve your problem.
Oh yea, the second option is to migrate to Unity 4.6 new GUI, which should take time unless you are pretty good with unity.
If you want to learn Unity 4.6 GUI, you can refer these links
Unity Official
Unity 4.6 tutorials by TheGameContriver

I am only posting on this because many come to this one and get lost. Here is how to make this work in Unity5.3 at the time of this response.
This is in C#
Simply use the GameController game object to attach the script to. Second create a UI text. Toy only call it score or scoretext for your own referral otherwise the name itself does not matter.
using UnityEngine;
using UnityEngine.UI;///needed to reference the new UI setup in this script type
using System.Collections;/// <summary>
/// allows collections of related information.
/// </summary>
public class GameController : MonoBehaviour {
public GameObject targets;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text Text; /// <summary>
/// change this because you dont actually use the words UI or GUI. Thats just for the reference and not clarified by instructors.
/// </summary>
private int score;
void Start()
{
score = 0;
UpdateScore();
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()///this depends on the above using System.Collections
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(targets, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
Text.text = "Score: " + score;
}
}

Confirmed. In the GameController.cs file, change the declaration of public GUIText scoreText to public Text scoreText, and then it will let you drag it on the Game Controller as the video shows.
Update your Unity tutorials, peoples! Just spent an hour trying to figure this out!

One more thing...check the Z position. My UI looked perfect head on in the scene view, but my text never showed in the game...then I rotated the scene view and found my text was way behind the camera. Seems when you add something to the UI, the z value is somewhat random.

Related

Unity UI not working properly ONLY on Windows

I have been working on figuring out what is going on with my game's UI for at least two days now, and no progress.
Note that this is a mobile game, but I was asked to build for Windows for visualization and presentation purpose.
So the problem is that when I run my game on the Unity Editor, Android, iOS and Mac platforms the UI works just perfect, but then when I run the game on Windows the UI still works fine UNTIL I load a specific scene.
This specific scene is a loading screen (between main menu and a level) when the level finished async loading, a method called MoveObjects is called in a script in the loading screen, to move some objects that where spawned in the loading screen scene into the level scene (this is not the issue though, since I already try without this method and the problem on the UI persist).
Once the logic of this MoveObjects method is done, a start button is enabled in the loading screen, for the player to click and start playing (I did try moving the start button to the level scene, since maybe it not been a child of the currently active scene could be the issue, but the problem still persist). Is at this point that the UI is partially broken, what I mean with this is, that I can see buttons (and some other UI elements like a scrollbar) changing color/state when the mouse moves over them, but I cannot click on them anymore (the button wont even change to the pressed state).
Also note that I tried creating a development build to see if there was any errors in the console, and I notice that this problem is also affecting the old UI system, so I was not able to interact with the development console anymore.
Also also, note that if I grab and drag the scrollbar before this issue appear, and I keep holding down on the scrollbar until this happens, the mouse gets stuck on the scrollbar, meaning that I cannot interact with the UI anymore, but the scrollbar will still move with the mouse.
I already check that this things are not the source of the problem:
Missing EventSystem, GraphicRaycaster or InputModule.
Another UI element blocking the rest of the UI.
Canvas is Screen Space - Overlay so there is no need for a camera reference.
I only have one EventSystem.
Time.timeScale is 1.
I am not sure what else I could try, so if anyone has any suggestions, I would appreciate it. Thanks.
P.S: I am sorry to say that I cannot share any code or visual material or examples due to the confidentiality.
A major source for a non-working UI for me has always been another (invisible) UI object blocking the raycast (a transparent Image, or a large Text object with raycast on).
Here's a snippet I put together based on info found elsewhere, I often use it to track objects that are masking the raycast in complex UI situations. Place the component on a text object, make sure it's at least few lines tall, as the results will be displayed one under another.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class DebugShowUnderCursor : MonoBehaviour
{
Text text;
EventSystem eventSystem;
List<RaycastResult> list;
void Start()
{
eventSystem = EventSystem.current;
text = GetComponent<Text>();
text.raycastTarget=false;
}
public List<RaycastResult> RaycastMouse(){
PointerEventData pointerData = new PointerEventData (EventSystem.current) { pointerId = -1, };
pointerData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);
return results;
}
void Update()
{
list= RaycastMouse();
string objects="";
foreach ( RaycastResult result in list)
objects+=result.gameObject.name+"\n";
text.text = objects;
}
}

deal with Unity 5 UI in augmented reality app

I'm trying to make an augmented reality application with vuforia and unity.
whenever it recognize the image target, it must tell a story by showing text , and it should enable the user to press next and back to go on reading the different parts of this story, I'm totally new to unity and don't know how to handle with UI throughout scripting, I need some help on how to accomplish the part of "going forward and backward on showing the story by hitting Next and Back buttons", and all these parts of story should be related to the same image target in the same scene.
I appreciate it if you help me with an example code.
You should create some script that attach on trackable object, maybe something like this.
public class DataBook {
string[] dataBook;
string idText;
bool isActive;
}
Then you must create another script to set that trackable object is active or not, this link can help you to get that.
https://developer.vuforia.com/forum/faq/unity-how-do-i-get-list-active-trackables
Then after you get the active trackable object, you can set the dialog from the book by create another controller script for button, example
public void Next() {
DataBook[] books = FindObjectsOfType<DataBook>(); // if the object more than one, it will be more easy if it only the one
foreach (var book in books)
{
if (book.isActive) {
book.idText += 1;
textUI.text = book.dataBook[idText]; //textUI assign to object text on canvas
}
}
}
you can learn about unity UI Button on this :
https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button
Good luck

Turning an avatar into a 3rd person character

I just learned how easy it is to simply drag a 3rd person character controller prefab (from Unity's standard assets package) and drop it into the hierarchy.
Using the WSAD and Space keys feels pretty natural, so I wondered if I could apply the same character controller to a customized avatar.
Using the free AutoDesk Character Generator (https://charactergenerator.autodesk.com/) I created one (fbx file) and imported it into Unity, so now I have my own character prefab.
I, then, searched for the steps to animate it just like a a 3rd person character controller, with the following article coming up first, but I wonder if I always have to do all the steps?
http://blogs.unity3d.com/2014/04/14/turn-your-character-into-a-player/
Once you have a customized character in the form of a Unity prefab, should do still go through all these steps, or is there a simpler way of animating your avatar; e.g. adding the basic necessary scripts?
That article gives a good overview of what is required.
However, you can essentially skip almost all those steps when using autodesk character generator.
Here is a quick way:
Set your FBX to be a mecanim humanoid
Drag an mecanim animator controller onto it
Write your code to set the animator states (eg: speed, jumping, etc)
To do that:
Export from Autodesk as "Unity FBX" format to get YourCharacter_Unity.fbx
Drag the FBX into the unity project files
Click on the YourCharacter_Unity FBX in project (blue cube), select "RIG" tab in inspector, and change Animation type to "Humanoid" (which maps it to the Mecanim system).
Drag the FBX from the project into the scene.
Go to the Asset Store and import "Mecanim Locomotion Starter Kit" (which has a basic locomotion controller and a set of animations)
Drag the "Locomotion Setup/Locomotion/Locomotion.controller" onto the "controller" variable on your character's Animator component.
Untick "apply root motion"
Now, if you hit run you will see your character standing there with idle motions. If you double click on the animator controller on your character it will open up the Mecanim Animtor window and you can manually set the animation state. Try changing the speed to 1.0 and you will see him walk/run.
Note: In your character's Animator component if you checkmark "Apply root motion", then the feet animation will cause your avatar to automatically move when his speed > 0.
You say you are using a CharacterController, so here is a very simple script that references the character controller to get the current speed, and then set the speed on the Animator:
using UnityEngine;
using System.Collections;
public class CharacterAnimator : MonoBehaviour {
public CharacterController controller;
public Animator animator;
private int speedid;
void Start () {
animator = GetComponentInChildren<Animator>();
controller = GetComponent<CharacterController>();
speedid = Animator.StringToHash("Speed");
}
void Update () {
float speed = controller.velocity.magnitude;
animator.SetFloat(speedid, speed);
}
}

Microsoft Visual Studio Objects

Hello is it possible to create an object that would function like a button?
Because I'm making a room management system for a hotel and the manager wants me to put a graphical representation of the rooms. I'm thinking it would be user friendly if I create an object that would represent the room e.g (rectangle) because I think it's too awful if I put many buttons in it. (it's too painful in the eyes).
The object should be clickable because when the user clicks or double clicks it. The room details would appear.
Thank you very much...
Yes, it is. All of the controls (as long as they inherit from Control, which basically all UI elements do) have a Click-Event, which you can register to so you get notified when it is clicked.
If you tell me if you are using WinForms or WPF I can give you an example of drawing a custom clickabel object.
You can either just set the size of a button to represent the room, or you can catch the Click event of any element you like to use to represent the room, for example a Panel.
You can also create a class that inherits from a control and implements some more features, that way it's easy to reuse it. Example:
public class Room : Panel {
// perhaps something to keep track of what room it is
private int _id;
// a constructor that sets the data that you need
public Room(int id) {
_id = id;
}
protected override OnClick(EventArgs e) {
// here you can handle the click
}
}
You create an object that would inherit from Control, and do custom drawing code using System.Drawing, It's a pretty simple task. With Control you're exposed to regular events like MouseDown, MouseUp, MouseEnter, MouseLeave, OnPaint, PaintBackground. These are events you're going to want if you add effects.

Coded UI Test without Element Detection

Is there any way to create a coded UI test for a WPF application that only detects the parent window element? We are using a component suite that does not support Coded UI tests, but I would still like to be able to automate the UI for testing purposes. Ideally, such a solution would detect the parent window element, then use pixel offsets for automating any button presses, etc.
Thanks.
You can use the Coded UI Test Builder to discover the properties you need, but the basic method for getting a window is pretty simple.
Here's a really simple class representing a window:
using System;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;
public class MyWpfWindow : WpfWindow
{
public MyWpfWindow() : base()
{
this.SearchProperties[WpfWindow.PropertyNames.Name] = "My Wpf Window Name";
}
}
And here's a test
[CodedUITest]
public class MyWpfWindowUITests
{
[TestMethod]
public void MyWpfWindowExistsTest()
{
Assert.IsTrue(MyWpfWindow.Exists(5000), "The window was not found within five seconds");
}
}
While technically it is possible (Mouse.Click has overloaded version with x,y coordinates), it is not a good idea. Any change in control layout will break your test.
http://social.msdn.microsoft.com/Forums/en-US/a2c585ee-8db0-48c0-8825-fb1865631977/how-do-i-click-checkbox-inside-drawhighlight-method
This link has the code to click on the coordinates within a defined highlighted area

Resources