Unity Button dont want to close a canvas - c#

Hello i made a canvas in unity.
when the player preses the Esc button a canvas opens
In the canvas i made a button when the player clicks on the button the
Canvas need to close but nothing happens when i press the button.
Can somebody help me with this problem?
The Canvas
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
private Canvas PlayerPauseMenu;
// Use this for initialization
void Start()
{
PlayerPauseMenu = GetComponentInChildren<Canvas>();
}
// Update is called once per frame
void FixedUpdate()
{
HandleInput();
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
PlayerPauseMenu.enabled = true;
}
}
public void CloseCanvas()
{
PlayerPauseMenu.enabled = false;
}
}

Related

OnTriggerEnter2D doesn't work after switching scenes

I have a game that is similar to "Flappy Bird" and I have main menu where I can start game and change skin of a pigeon. My skin collection is implemented with scroll rect and in the center there is a trigger which starts an animation of scaling a pigeon, it works fine until I click "start" and the scene changes to game and when I return to my main menu and click "skins" this trigger doesn't work anymore.
Script what is attached to all scroll rect elements to detect collisions with trigger:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResizeFieldScript : MonoBehaviour
{
private Animator _anim;
private void Start()
{
_anim = GetComponent<Animator>();
}
public void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log("Trigger is working");
if(collider.tag == "ResizeField")
{
Debug.Log("Condition is working");
_anim.SetBool("isInTrigger", true);
}
}
public void OnTriggerExit2D(Collider2D collider)
{
_anim.SetBool("isInTrigger", false);
}
}
Script what is attached to an empty object to change scenes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
public class UIController : MonoBehaviour
{
[SerializeField] private List<string> sceneNameList;
private string sceneToFind;
private int index = 0;
public void SceneChanger()
{
sceneToFind = EventSystem.current.currentSelectedGameObject.name;
foreach(string str in sceneNameList)
{
if(str == sceneToFind)
{
SceneManager.LoadScene(index);
index = 0;
break;
}
index++;
}
}
public void Exit()
{
Application.Quit();
}
public void BackMenu()
{
SceneManager.LoadScene(4);
}
}
OnTriggerEnter2D doesn't work after switching scenes. We could use OnTriggerEnter2D to jump scenes.
code show as below:
private void Update() {
// If E is pressed
if (Input. GetKeyDown(KeyCode. E)) {
// scene switching
SceneManager.LoadScene(4);
}
}
private void OnTriggerEnter2D(Collider collision) {
if (collision. tag == "ResizeField") {
// The UI prompts the user to press E to jump
EnterDialog.SetActive(true);
Debug.Log("Condition is working");
// _anim.SetBool("isInTrigger", true);
}
}
Hope it helps you.

Menu panels show in game by default as open

i'm making a 2D game and my Menu panels are showing when i press play on unity they show as opened is there anyway to make them closed and only show when i press on menu button. this is the picture from the game:
And this is the script for panel opener when i press the menu button:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PanelOpener : MonoBehaviour
{
public GameObject Panel;
public void OpenPanle()
{
if (Panel != null)
{
bool isActive = Panel.activeSelf;
Panel.SetActive(!isActive);
}
}
}
Disable panels at start with a:
private void Awake(){
Panel.SetActive(false);
}
Complete code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PanelOpener : MonoBehaviour
{
public GameObject Panel;
private void Awake(){
Panel.SetActive(false);
}
public void OpenPanle()
{
if (Panel != null)
{
bool isActive = Panel.activeSelf;
Panel.SetActive(!isActive);
}
}
}
Get yourself familiar with MonoBehaviour functions like Start, Awake, Update, FixedUpdate in the future.

Unity can't identify which button is beeing pressed

I've been trying to make the options in my game being selected by a keyboard input. I can highlight them, but I don't know how to make Unity identify which of the buttons is beeing pressed in order to do a certain action, it's giving me the NullReferenceException in line 28 of my code. The cript in question is the BattleSystem script, it's attached to the event system, the battleFirstButton is the fight button and the enterKey is "Z".
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class BattleSystem : MonoBehaviour
{
public GameObject battleFirstButton;
public KeyCode enterKey;
Button selectedButton;
// Start is called before the first frame update
void Start()
{
EventSystem.current.SetSelectedGameObject(null);
EventSystem.current.SetSelectedGameObject(battleFirstButton);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(enterKey))
{
selectedButton.onClick.Invoke();
}
}
public void SetSelectedButton()
{
selectedButton = GetComponent<Button>();
}
public void Fight()
{
print("Fight option submitted");
}
public void Act()
{
print("Act option submitted");
}
public void Item()
{
print("Item option submitted");
}
public void Mercy()
{
print("Get dunked o-, I mean, Mercy option selected");
}
}
selectedButton is a private variable potentially never set to anything, so it's null. Make sure it's set to something before you access it.
Probably the simplest fix to the way you have it set up is:
void Update()
{
if (Input.GetKeyDown(enterKey))
{
// Gets the focused button
selectedButton = EventSystem.current.currentSelectedGameObject.GetComponent<Button>();
if (selectedButton != null)
{
selectedButton.onClick.Invoke();
}
}

How to know which prefab button I am clicking?

I made a couple of prefab buttons. When I click each one of them they go to the same scene, but I that scene to have different information according to which button I clicked. How can know which was the button I clicked? The function goArtistDetail is the one being called by every button.
I have this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonScriptTwo : MonoBehaviour
{
// Use this for initialization
void Start ()
{
Debug.Log("ButtonScriptTwo");
Debug.Log("counter: " + GlobalState.counter);
}
public void goArtistDetail(Button button)
{
GlobalState.counter++;
Application.LoadLevel("ArtistDetail");
}
}
Prefab of the Button
is there any reason why you are trying to use the same method for both calls other than that the same scene is being loaded? If not why not just have a different method for each buttons onClick and set a PlayerPref.
public void ButtonClick_1()
{
GoArtistDetail(1);
}
public void ButtonClick_2()
{
GoArtistDetail(2);
}
// C# Methods start with a Captial
private void GoArtistDetail(int refererBtn)
{
GlobalState.counter++;
PlayerPrefs.SetInt("Referer Button", refererBtn)
Application.LoadLevel("ArtistDetail");
}
An then in the ArtistDetail scene
private void Start()
{
int refererBtn = 1; //Default value
if(PlayerPrefs.HasKey("Referer Button"))
{
refererBtn = PlayerPrefs.GetInt("Referer Button");
PlayerPrefs.DeleteKey("Referer Button");// Remove it if it is use once
}
//Evaluate refererBtn to show what info is relevant
}

Making volume slider in Unity

Game starts, the music begins to play, but it's too annoying and want to mute or just make it quieter. Like games, there's setting menu, which I thought it would be good to be in next scene, and there I want to put slider.
But I got errors.
Script:
using UnityEngine;
using System.Collections;
public class Music : MonoBehaviour
{
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
public AudioClip[] soundtrack;
// Use this for initialization
void Start()
{
if (!GetComponent<AudioSource>().playOnAwake)
{
GetComponent<AudioSource>().clip = soundtrack[Random.Range(0, soundtrack.Length)];
GetComponent<AudioSource>().Play();
}
}
// Update is called once per frame
void Update()
{
if (!GetComponent<AudioSource>().isPlaying)
{
GetComponent<AudioSource>().clip = soundtrack[Random.Range(0, soundtrack.Length)];
GetComponent<AudioSource>().Play();
}
}
}
You use AudioSource.volume to change the volume. When you create a Slider, you can get the value of the slider with Slider.value. So, take Slider.value and assign it to AudioSource.volume.
To create s Slider, go to GameObject->UI->Slider. Make sure that Min Value is 0 and Max Value is 1. Also make sure that Whole Numbers check box is NOT checked. Drag the Slider to the volume Slider slot in this script from the Editor.
Note:
If you are going to use a component more than once, cache it to a global variable instead of doing GetComponent<AudioSource>() multiple times or using it in the Update() function.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Music : MonoBehaviour
{
public AudioClip[] soundtrack;
public Slider volumeSlider;
AudioSource audioSource;
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
// Use this for initialization
void Start()
{
audioSource = GetComponent<AudioSource>();
if (!audioSource.playOnAwake)
{
audioSource.clip = soundtrack[Random.Range(0, soundtrack.Length)];
audioSource.Play();
}
}
// Update is called once per frame
void Update()
{
if (!audioSource.isPlaying)
{
audioSource.clip = soundtrack[Random.Range(0, soundtrack.Length)];
audioSource.Play();
}
}
void OnEnable()
{
//Register Slider Events
volumeSlider.onValueChanged.AddListener(delegate { changeVolume(volumeSlider.value); });
}
//Called when Slider is moved
void changeVolume(float sliderValue)
{
audioSource.volume = sliderValue;
}
void OnDisable()
{
//Un-Register Slider Events
volumeSlider.onValueChanged.RemoveAllListeners();
}
}
You can learn more about Unity's UI here.

Categories