Unity multiplayer UI button script - unity3d

I have a multiplayer 2D game made in Unity and I wanted to put some onscreen buttons to be able to control it on the telephone. The problem is that when I put the Event Trigger on the button it uses the function from the script that has to use, but it can't open other functions called in the main one. In my code, I try to open the function TryFireBullet() whenever I am pressing the button and Debug.Log shows me that TryFireBullet() is opened, but the functions inside it are not opened at all. (when I press the button, Debug.Log() shows me "works", "works2" and no "works3"..)
Any ideas why it does not work and how to fix it?
Here is the problem part of the code:
public void TryFireBullet()
{
Debug.Log("works");
//if (ultimul_glont == 0 || Time.time > ultimul_glont + Delay_Bullet)
//{
ultimul_glont = Time.time;
Debug.Log("works2");
CmdFireBullet();
//}
}
[Command]
public void CmdFireBullet()
{
Debug.Log("works3");
GameObject bullet = Instantiate(bulletPrefab, gunTip.position, Quaternion.identity) as GameObject;
NetworkServer.Spawn(bullet);
RpcAdaugaViteza(bullet);
}
Here is the full code:
https://pastebin.com/WaWbQvTw
p.s. I can not use just a main function for my button because I need Server Commands

Related

Unity 2D How to set touch button?

I make a game for android and i need to have UI Joystick and UI Attack Button on the game screen. I already have the workable Joystick and Attack Button on Space key for keyboard.
Can someone told me how should i switch code from keyboard Input to Touch Input?
P.S. i'm sorry for my english.
if (Time.time >= nextAttackTime)
{
if (Input.GetKeyDown(KeyCode.Space))
{
Attack();
nextAttackTime = Time.time + 2.5f / attackRate;
}
}
try this one.
using UnityEngine;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
//Make sure to attach these Buttons in the Inspector
public Button YourButton,
void Start()
{
YourButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){ /// this method will active when press the button
if (Time.time >= nextAttackTime)
{
Attack();
nextAttackTime = Time.time + 2.5f / attackRate;
}
}
}
Another way would be to work with the unity Button script, apply it to the GameObject that represents the Button. Under Target Graphic add the corresponding Object with the graphic. Under On Click() add an Event, put the gameobject that has your Attack Function in (None Object) and add the Attack function under Function.
here are some infos about how the button works:
https://docs.unity3d.com/2018.3/Documentation/Manual/script-Button.html
edit: was also answered here Unity Button code not working

Unity, I have problem with DontDestroyOnLoad to keep tracking in different scence

im new in unity and i have a problem
I am making a game that have 2 scence(Main Menu Scence and Game Scence), i put my music on Main Menu scence. I make a empty game object and i attach audio source there(music) , and i also attach script like this :
First script
public static KeepTheMusicOn Instance;
void Awake()
{
if (!Instance)
Instance = this;
else
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
With that script i can keep music play in second scence wihtout restart the music, and in the main menu scence i have settings that have button to mute the music , the button will run my second script .
Second Script:
public AudioSource mainMusic;
public void Update()
{
DontDestroyOnLoad(mainMusic);
}
public void MusicOnOff()
{
if (mainMusic.isPlaying)
{
mainMusic.Pause();
}
else
{
mainMusic.UnPause();
}
}
My problem is when i start the game so im in my main menu scence i can mute the music with the button, but when i go to game scence and i back to menu, the button dont do anything.
So that is my problem, i hope anyone can help me. Sorry for my bad english.
Sounds like when switching scenes you destroy the button. When you them go back to the main menu you destroy the duplicate instance of your audio controller thing => references configured in the Button are lost.
In your case since you use a public Singleton anyway you could as well (ab)use it and put a component on the Button itself instead (thus the reference can not get lost) and do something like e.g.
[RequireComponent(typeof(Button))]
public class MusicButton : MonoBehaviour
{
[SerializeField] private Button button;
private void Awake()
{
if(!button) button = GetComponemt<Button>();
// dynamically add the callback
// it won't appear in the editor but get called in onClick
button.onClick.AddListener(OnClicked);
}
private void OnClicked()
{
KeepTheMusicOn.Instance.MusicOnOff();
}
}
If you prefer seeing it in the editor you can ofcourse as well rove it from Awake, make the OnClicked public and reference it in the button's onClick event manually.

Unity 5: Game view - Run Time - SpaceBar Causing Issue

Game View- Camera Display
When I click the Space Bar for the player to jump, the Display drop down menu pops up and the player doesn't jump. However, the player can move upon all key presses.
Here's the information that I have:
1) Everything worked and functioned properly.
2) I added a health bar to my boss.
3) I created a second canvas (First canvas was for my Player's HP).
4) I made the Boss HP bar render mode: World Space.
5) I attached the canvas to the boss controller in the hierarchy as a child.
6) The code I use for Player Jump is Input.GetKeyDown(KeyCode.Space).
7) The mouse curser is inside the Game View whilst testing the SpaceBar Jump.
8) I'm developing in Unity 2018 5.3 2D mode.
Official Question('s):
1) Why does the Spacebar causing the camera display drop menu to appear?
2) How do I fix this?
Edit / Additional Content:
Here's my Jump script
public float jump1 = 5.0f;
private bool onGround;
//private bool dblJump; //Not implemented yet
public Rigidbody player;
void Start () {
player = GetComponent<Rigidbody>();
onGround = true;
}
// Update is called once per frame
void Update () {
if (onGround == true) {
if (Input.GetKeyDown(KeyCode.LeftShift))// KeyCode.Space
{
player.velocity = new Vector3(0, jump1, 0);
onGround = false;
// Debug.Log("The onGround is False");
}
}
}
Keep in mind that I have temporarily changed my jump to LeftShift. However, my problem persist with the space bar, even when I click it with left shift as my jump. SpaceBar seems to summon the drop down menu for the camera display. (I can't seem to catch the drop down menu with a screen shot because it goes away upon a click)
Also Note - I'm inside a class called PlayerJump : MonoBehavior.
It seems like it's a known issue with some versions of Unity 5.3, I have a few solutions you can try :
Drag you game window somewhere else in the editor
Enable the "Maximise on play" button
Attach this script to your drop-down element :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DropdownScript : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
void Start()
{
dropDown = GetComponent<Dropdown>();
dropDown.interactable = false;
}
public void OnPointerEnter(PointerEventData ped)
{
dropDown.interactable = true;
}
public void OnPointerExit(PointerEventData ped)
{
dropDown.interactable = false;
}
}
Otherwise update you Unity version if it's not the latest release? I am not experiencing this issue but many other users are apparently.

How to prevent mouse clicks from passing through GUI controls and playing animation in Unity3D [duplicate]

This question already has answers here:
Detect mouse clicked on GUI
(3 answers)
Closed 4 years ago.
Description
Hi Guys need your help I faced problems with mouse clicks which pass through UI panel in Unity, that is, I have created pause menu and when I click Resume button, the game gets unpaused and the player plays Attack animation which is undesirable.What I want is when I click Resume button, Attack animation should not be played. The same problem if I just click on panel not necessarily a button and the more I click on UI panel the more Attack animation is played after I exit pause menu. Moreover, I have searched for solutions to this issue and was suggeted to use event system and event triggers but since my knowledge of Unity is at beginner level I could not properly implement it. Please guys help and sorry for my English if it is not clear)) Here is the code that I use:
The code:
using UnityEngine;
using UnityEngine.EventSystems;
public class PauseMenu : MonoBehaviour {
public static bool IsPaused = false;
public GameObject pauseMenuUI;
public GameObject Player;
private bool state;
private void Update() {
//When Escape button is clicked, the game has to freeze and pause menu has to pop up
if (Input.GetKeyDown(KeyCode.Escape)) {
if (IsPaused) {
Resume();
}
else {
Pause();
}
}
}
//Code for Resume button
public void Resume() {
//I was suggested to use event system but no result Attack animation still plays once I exit pause menu
if (EventSystem.current.IsPointerOverGameObject()) {
Player.GetComponent<Animator>().ResetTrigger("Attack");
}
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
IsPaused = false;
}
//this method is responsible for freezing the game and showing UI panel
private void Pause() {
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
IsPaused = true;
}
//The code for Quit button
public void QuitGame() {
Application.Quit();
}
}
Im not sure if i understood your problem, but it sounds like somewhere in your code you start an attack when the player does a left click.
Now your problem is that this code is also executed when the player clicks on a UI element, for example in this case the Resume button?
You tried to fix this problem, by resetting the attack trigger of the animator, i think it would be a better solution to prevent the attack from starting instead of trying to reset it later.
EventSystem.current.IsPointerOverGameObject() returns true if the mouse is over an UI element.
So you can use it to modify your code where you start your attack:
... add this check in your code where you want to start the attack
if(EventSystem.current.IsPointerOverGameObject() == false)
{
// add your code to start your attack
}
...
Now your attack will only start if you are not over a UI element

IsPointerOverGameObject returns true for different ui text in unity

I have a canvas in unity 2d scene , Inside it I have 3 UI Text elements , I am attaching the below script to 2 of the UI elements
void Update()
{if (Input.GetMouseButtonDown (0)) {
if (EventSystem.current.IsPointerOverGameObject ()) {
//Application.CaptureScreenshot("Bla.png");
//ShareImage(Application.persistentDataPath + "/Bla.png", "dasdas", "dsadaS", "dasdas");
Debug.Log ("Screenshot taken");
}
}
}
The problem is happening that If i click anything inside the canvas IsPointerOverGameObject is return always true , I created another canvas but same problem. It's like its dealing with all UI elements being clicked on each time I click any UI text element.
I am creating a menu of UI text items and each item must has it's own action , but here each time i am clicking it's firing the same action for all
The code you attached works perfectly fine on my machine. I was able to replicate your problem by attaching the script to the Canvas which the parent of my text. Make sure that you did not attach the script to the Canvas but only on each individual Text.
If this is not the problem,there are many other ways to do this in Unity. Sometimes, some of the API don't work well because of the way your UI is setup. You can try the method below:
using UnityEngine.EventSystems;
public class Clicker: MonoBehaviour, IPointerClickHandler
{
void Update()
{
}
public void OnPointerClick(PointerEventData eventData)
{
//Application.CaptureScreenshot("Bla.png");
//ShareImage(Application.persistentDataPath + "/Bla.png", "dasdas", "dsadaS", "dasdas");
Debug.Log("Screenshot taken");
}
}