Unity3D GUI.Label is not displayed - unity3d

I am currently trying to make "Welcome!" string and a button appear on screen by using the GUI Label and GUILayout Button, but it does not appear and there are not any errors that I know of. Unity emulator is ok, but the "Welcome!" string is not displayed in android.
Here is my code, can someone please tell me my problem and if I might have forgotten to do something.
public class MainMenu : MonoBehaviour
{
public GUISkin Skin;
public Texture btnTexture;
public void Awake() { }
public void OnGUI()
{
if (this.Skin != null)
{
GUI.skin = this.Skin;
}
GUI.skin.button.fontSize = 30;
Rect content = new Rect(30, 100, Screen.width-60, Screen.height-200);
GUILayout.BeginArea(content);
GUILayout.BeginHorizontal();
GUIStyle TextStyle = new GUIStyle(GUI.skin.label);
TextStyle.fontSize = 50;
// Load and set Font
Font myFont = (Font)Resources.Load("font/stingray", typeof(Font));
GUI.skin.font = myFont;
// Set color for selected and unselected
TextStyle.normal.textColor = Color.yellow;
TextStyle.hover.textColor = Color.yellow;
// Display and set the style in string
GUI.Label(new Rect(50,50,300,70), "Welcome!", TextStyle);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Join", GUILayout.Width(300), GUILayout.Height(80)))
{
SceneManager.LoadSceneAsync("SingleMenu");
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
void Start () { }
void Update () { }
}

Related

How to add button in scroll View using script in unity

I am new to unity and am using unity 2020.3.26f1 . I am receiving an array of names from server. I want to make buttons dynamically using those names inside scroll view using c# script and assign on Click() that simply prints the name of button when its clicked. I just don't know how to create button dynamically. Following is the script I have attached to scroll View;
public string allNames;
void Start()
{
StartCoroutine(getNames());
}
IEnumerator getNames()
{
UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
allNames = www.downloadHandler.text;
allNames = allNames.Replace("[", "");
allNames = allNames.Replace("]", "");
allNames = allNames.Replace("\"","");
string[] separatedNames = allNames.Split(',');
for (int i = 0; i < separatedNames.Length; i++)
{
Debug.Log(separatedNames[i]);
//make buttons here and attach them to scroll View
}
}
}
I found a video that applied #ShafqatJamilKhan suggestion. Posting my code here for reference.
//content reference of scroll view
[SerializeField] Transform contentPanel;
[SerializeField] GameObject buttonPrefab;
void Start()
{
StartCoroutine(getNames());
}
IEnumerator getNames()
{
UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
string allNames = www.downloadHandler.text;
allNames = allNames.Replace("[", "");
allNames = allNames.Replace("]", "");
allNames = allNames.Replace("\"","");
// prefab button y position and yPosition should be the same.
float yPosition = 115;
string[] separatedNames = allNames.Split(',');
for (int i = 0; i < separatedNames.Length; i++)
{
GameObject button = (GameObject)Instantiate(buttonPrefab);
string name = separatedNames[i];
button.GetComponentInChildren<Text>().text = name;
button.GetComponent<Button>().onClick.AddListener(
// your function whatever you want to do
() => { customFunction(name); });
// applying y positions so the buttons dont overlap
button.transform.SetPositionAndRotation(new Vector3(0.0f, yPosition, 0.0f), new Quaternion(0.0f, 0.0f, 0.0f,0.0f));
button.transform.SetParent(contentPanel,false);
yPosition -= 35;
}
}
}
Make a nice button and save it as prefab.
Instantiate it or Pool it.
Add onClick events.
GameObject buttonPrefab;
void MyAwesomeCreator()
{
GameObject go = Instantiate(buttonPrefab);
var button = GetComponent<UnityEngine.UI.Button>();
button.onClick.AddListener(() => FooOnClick());
}
void FooOnClick()
{
Debug.Log("Ta-Da!");
}
Copied from Unity Forum

Unity Banner is not showing

My Banner Ad does show in test mode but without testmode not.
I used a code template from the unity website.
I also asked the unity ads support but they couldn't find the error.
they send me a video of my application,and in this video the banner ad worked.
Here is my code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
public class newadsystem : MonoBehaviour
{
// For the purpose of this example, these buttons are for functionality testing:
[SerializeField] Button _loadBannerButton;
[SerializeField] Button _showBannerButton;
[SerializeField] Button _hideBannerButton;
[SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;
[SerializeField] public string _androidAdUnitId = "Banner_Android";
[SerializeField] string _iOsAdUnitId = "Banner_iOS";
public string _adUnitId = "Banner_Android";
void Start()
{
Advertisement.Initialize("4395157",false,true);
// Disable the button until an ad is ready to show:
_showBannerButton.interactable = true;
_hideBannerButton.interactable = true;
// Set the banner position:
Advertisement.Banner.SetPosition(_bannerPosition);
// Configure the Load Banner button to call the LoadBanner() method when clicked:
_loadBannerButton.onClick.AddListener(LoadBanner);
_loadBannerButton.interactable = true;
}
// Implement a method to call when the Load Banner button is clicked:
public void LoadBanner()
{
// Set up options to notify the SDK of load events:
BannerLoadOptions options = new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
};
// Load the Ad Unit with banner content:
Advertisement.Initialize("4395157", false, true);
Advertisement.Banner.Load(_adUnitId, options);
Advertisement.Initialize("4395157", false, true);
}
// Implement code to execute when the loadCallback event triggers:
void OnBannerLoaded()
{
Debug.Log("Banner loaded");
// Configure the Show Banner button to call the ShowBannerAd() method when clicked:
_showBannerButton.onClick.AddListener(ShowBannerAd);
// Configure the Hide Banner button to call the HideBannerAd() method when clicked:
_hideBannerButton.onClick.AddListener(HideBannerAd);
// Enable both buttons:
_showBannerButton.interactable = true;
_hideBannerButton.interactable = true;
}
// Implement code to execute when the load errorCallback event triggers:
void OnBannerError(string message)
{
Debug.Log($"Banner Error: {message}");
// Optionally execute additional code, such as attempting to load another ad.
}
// Implement a method to call when the Show Banner button is clicked:
void ShowBannerAd()
{
// Set up options to notify the SDK of show events:
BannerOptions options = new BannerOptions
{
clickCallback = OnBannerClicked,
hideCallback = OnBannerHidden,
showCallback = OnBannerShown
};
// Show the loaded Banner Ad Unit:
Advertisement.Initialize("4395157", false, true);
Advertisement.Banner.Show(_adUnitId, options);
}
// Implement a method to call when the Hide Banner button is clicked:
void HideBannerAd()
{
// Hide the banner:
Advertisement.Banner.Hide();
}
void OnBannerClicked()
{
Debug.Log("Banner Clicked!");
}
void OnBannerShown()
{
Debug.Log("Banner Shown!");
}
void OnBannerHidden()
{
Debug.Log("Banner Hidden");
}
void OnDestroy()
{
// Clean up the listeners:
_loadBannerButton.onClick.RemoveAllListeners();
_showBannerButton.onClick.RemoveAllListeners();
_hideBannerButton.onClick.RemoveAllListeners();
}
}
I looked into the android device log and there was: "Unity : Banner Error: UnityAds is not initialized."
but i call several times the initialize function.
PS: i am not very good at english.
Have a look at Start (), your code:
Advertisement.Initialize("4395157",false,true);
// Disable the button until an ad is ready to show:
_showBannerButton.interactable = true;
_hideBannerButton.interactable = true;
And then at OnBannerLoaded ()
// Enable both buttons:
_showBannerButton.interactable = true;
_hideBannerButton.interactable = true;
But those button are already interactable = true.
Maybe you need to change Start () like this:
Advertisement.Initialize("4395157",false,true);
// Disable the button until an ad is ready to show:
_showBannerButton.interactable = false;
_hideBannerButton.interactable = false;
Update 1
Try to change your code the following way:
void Start()
{
_showBannerButton.interactable = false;
_hideBannerButton.interactable = false;
Advertisement.Initialize("4395157",false,true);
_loadBannerButton.onClick.AddListener(LoadBanner);
_showBannerButton.onClick.AddListener(ShowBannerAd);
_hideBannerButton.onClick.AddListener(HideBannerAd);
_loadBannerButton.interactable = true;
}
public void LoadBanner()
{
BannerLoadOptions options = new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
};
if (Advertisement.isInitialized) {
Advertisement.Banner.Load(_adUnitId, options);
} else Debug.LogWarning ("Adverisement not initialized! Try again later");
}
void OnBannerLoaded()
{
Debug.Log("Banner loaded");
BannerOptions options = new BannerOptions
{
clickCallback = OnBannerClicked,
hideCallback = OnBannerHidden,
showCallback = OnBannerShown
};
Advertisement.Banner.SetPosition(_bannerPosition);
_showBannerButton.interactable = true;
_hideBannerButton.interactable = true;
}
void ShowBannerAd()
{
Advertisement.Banner.Show(_adUnitId, options);
}

How to Get UI button to Stay in a Pressed State in Unity 3D

In Unity 3D, when you select a button, it will stay pressed until you click outside the button and basically goes back to its Normal Color. The problem is, I want the button to stay pressed (color-wise) when I click outside the button or scene. Does anyone know how to keep a button pressed or "selected" after clicking it?
You can use Unity UI Toggle (as said by Muhammad). Change the design to remove the checkmark and make it looking like a button.
With this component you have the state 'isOn' that you can use and change the color when selected for example.
public class Button_Stay_Pressed : MonoBehaviour
{
private Button btn;
[SerializeField]
private Sprite normal_sprite;
[SerializeField]
private Sprite pressed_sprite;
void Awake()
{
btn = gameObject.GetComponent<Button>();
btn.image.sprite = normal_sprite;
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
btn.image.sprite = pressed_sprite;
}
}
Here is the C# script using delegate that'll (toggle between buttons) set clicked button to "on/pressed" (custom) colour and change the other button(s) with this script attached to them to deselect colour, Copy & paste solution(attach this script to buttons you want to toggle between):
using TMPro;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Functionality: Control UI Button clicks selected colour
/// Author: Akrima Huzaifa
/// Date Created: 1st-December-2022
/// </summary>
public class BtnClickHandler : MonoBehaviour
{
public delegate void OnBtnClick(BtnClickHandler obj);
public static event OnBtnClick onBtnClick;
public Button poleBtn;
public Image poleImage;
private void Awake()
{
if (GetComponent<Button>())
{
poleBtn = GetComponent<Button>();
poleImage = GetComponent<Image>();
poleBtn.onClick.AddListener(delegate { OnBtnClick(); });
}
}
private void OnEnable()
{
onBtnClick += SelectDeselectBtn;
}
private void OnDisable()
{
onBtnClick -= SelectDeselectBtn;
}
public void SelectDeselectBtn(BtnClickHandler obj)
{
if (obj == this)
{
OnClick_ObjButtonSelected();
}
else
{
DeselectBtn();
}
}
public void OnBtnClick()
{
BtnClickHandler.onBtnClick.Invoke(this);
}
//---For UI---
public void OnClick_ObjButtonSelected()
{
if (!poleImage.fillCenter)
{
print("if color");
poleImage.fillCenter = true;
poleImage.color = new Color32(230, 230, 230, 255);
poleImage.transform.GetComponentInChildren<TextMeshProUGUI>().color = new Color32(255, 115, 0, 255);
}
else
{
DeselectBtn();
}
}
public void DeselectBtn()
{
print("else color");
poleImage.fillCenter = false;
poleImage.color = new Color32(178, 178, 178, 255);
poleImage.transform.GetComponentInChildren<TextMeshProUGUI>().color = new Color32(255, 255, 255, 255);
}
}

MovieTexture Never Plays In Build

I have written a script to play OGG files as a MovieTexture, i've tried both embedded asset files and also from the web. The problem I'm having is that the videos play in debug move (When I hit the play button and test in the "Game" tab) but they never work when I build to an executable..
using UnityEngine;
namespace Assets.Scripts
{
[RequireComponent(typeof(AudioSource))]
public class VideoScreen : MonoBehaviour
{
public string videoUrl;
public bool autoPlay = true;
public bool loop = true;
public bool playAudio = true;
public float opacity = 1.0f;
private bool hasLoaded;
private MovieTexture movieTexture;
public void Start ()
{
if (string.IsNullOrEmpty(videoUrl))
{
return;
}
var data = new WWW(videoUrl);
movieTexture = data.movie as MovieTexture;
}
public void Update()
{
if (movieTexture.isReadyToPlay && !hasLoaded)
{
renderer.material = new Material(Shader.Find("Custom/Unlit Transparent Color")) { mainTexture = movieTexture };
audio.clip = movieTexture.audioClip;
SetLoop(loop);
if (autoPlay)
{
Play();
}
hasLoaded = true;
}
var textureColor = renderer.material.color;
textureColor.a = opacity;
renderer.material.color = textureColor;
}
private void Play()
{
movieTexture.Stop();
movieTexture.Play();
if (playAudio)
{
audio.Stop();
audio.Play();
}
}
private void Pause()
{
movieTexture.Pause();
if (playAudio)
{
audio.Pause();
}
}
private void Stop()
{
movieTexture.Stop();
if (playAudio)
{
audio.Stop();
}
}
private void SetLoop(bool loopStatus)
{
movieTexture.loop = loopStatus;
if (playAudio)
{
audio.loop = loopStatus;
}
}
}
}
Can anyone shed any light on this behaviour?
Thanks
Turns out the custom Transparent Diffuse shader I was using was causing the issue! Doh!!
renderer.material = new Material(Shader.Find("Custom/Unlit Transparent Color")) { mainTexture = movieTexture };
now becomes
renderer.material.mainTexture = movieTexture;

Decouple controller logic from Unity3D GUI controls using C#, like fade OnGUI

I'm failing to understand how to decouple business logic of a controller and view for Unity3D GUI controls.
For example, if I have a GUI.Box, how would I implement a controller to fade in or out from the OnGUI lifecycle stage of the view?
View
using UnityEngine;
public class ExampleView : MonoBehaviour {
protected void OnGUI () {
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
}
If I instantiate a controller to change alpha of GUI.color it would need notification of Update() from the main view thread.
To roughly encapsulate functionality, if this were a single script it could be implemented as:
using UnityEngine;
public class ExampleView : MonoBehaviour {
private Color color;
protected void Start () {
color = Color.white;
}
protected void OnGUI () {
GUI.color = color;
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
protected void Update () {
if(color.a > 0)
color.a -= Time.deltaTime / 3;
}
}
Akin to how iTween animates changes to properties using iTween.fadeTo(gameObject, ... how can this be implemented for Unity3d GUI controls using statements like FadeOut()?
There's probably no way to target individual GUI controls unless multiple controller instances are specified OnGUI(). However, it would be cool to control isolated GUI instances such as fading in a GUI.Box followed by GUI.Label.
Are you looking for something like this?:
using UnityEngine;
public class ExampleView : MonoBehaviour {
private Color color;
private bool bFadeIn = false;
private bool bFadeOut = false;
protected void Start () {
color = Color.white;
}
public void FadeOut(){
bFadeOut = true;
bFadeIn = false;
}
public void FadeIn(){
bFadeIn = true;
bFadeOut = false;
}
protected void OnGUI () {
GUI.color = color;
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
protected void Update () {
if(bFadeOut && color.a > 0.0)color.a -= Time.deltaTime / 3;
if(bFadeIn && color.a < 1.0)color.a += Time.deltaTime / 3;
}
}
You might also want to include a flag to determine when the control is invisible and, if invisible, skip the full GuiRender function.
Dont know if this is what you are looking for, but its a simple way to add fade effect to gui..
using UnityEngine;
using System.Collections;
/**Fade In/Out Instructions:
* 1.Create bool fadeIn. Create float alpha.
* 2.Call Fade() method at start of OnGUI().
* 3.Put 'GUI.color = new Color(1,1,1,alpha)' above the elements you want to fade'.
* 4.To fade in, fadeIn = true.
* 5.To fade out, fadeIn = false.
* 6.To deactivate buttons on fade out, wrap gui in 'if(alpha > 0)'
**/
public class MainMenuGUI : MonoBehaviour {
int buttonWidth;
int buttonHeight;
public float alpha;
public bool fadeIn;
// Use this for initialization
void Start () {
buttonWidth = 100;
buttonHeight = 50;
fadeIn = true;
}
void OnGUI(){
Fade();
GUI.color = new Color(1,1,1,alpha);
if(alpha > 0)
{
if (GUI.Button (new Rect ((Screen.width/2)-50, (Screen.height/2)-(buttonHeight*4/2), 100, 50), "PLAY"))
{
fadeIn = false;
Debug.Log("Play pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight), 100, 50), "SCORES"))
{
Debug.Log("Scores pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight*2), 100, 50), "OPTIONS"))
{
Debug.Log("Options pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight*3), 100, 50), "EXIT"))
{
Debug.Log("Exit pressed");
}
}
}
void Fade(){
if(fadeIn){
alpha = Mathf.Clamp(alpha+0.01f,0,1);
}else{
alpha = Mathf.Clamp(alpha-0.01f,0,1);
}
}
}
Good luck on your game :)