Unity - Start Method not running - c#

I'm new to Unity and i am following a flappy bird tutorial to get a little more familiar with the game engine. i'm following the CodeMonkey tutorial. i'm at the game over screen. this is the script i have attached to my GameOverWindow. but only the Awake() gets called. the start doesn't. because of this my event is not working so the Game over window does not show.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CodeMonkey.Utils;
public class GameOverWindow : MonoBehaviour
{
private Text scoreText;
// Start is called before the first frame update
private void Start()
{
Bird.GetInstance().OnDied += Bird_OnDied;
}
private void Awake()
{
scoreText = transform.Find("scoreText").GetComponent<Text>();
transform.Find("retryBtn").GetComponent<Button_UI>().ClickFunc = () => { UnityEngine.SceneManagement.SceneManager.LoadScene("GameScene"); };
Hide();
}
private void Bird_OnDied(object sender, System.EventArgs e)
{
scoreText.text = Level.GetInstance().GetPipesPassedCount().ToString();
Show();
}
// Update is called once per frame
private void Update()
{
}
private void Hide()
{
gameObject.SetActive(false);
}
private void Show()
{
gameObject.SetActive(true);
}
}

According to Unity docs
Start is called exactly once in the lifetime of the script. However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled. Start may not be called on the same frame as Awake if the script is not enabled at initialisation time.
So if GameOverWindow is disabled from the beginning, Start will not be executed, but Awake will. You can move your event initialization to Awake and it should work (as long as it's a problem with adding event, not code in event).

Related

I want to reset the level in Unity and don't reset the variable too

I want to reset level in Unity and don't reset the coin amount variable and the lose counter variable. I use playerprefs but it doesn't work to me the variable reset too.
public void EndGame()
{
LoseCounter++;
Invoke("Restart", restartDelay);
}
public void Restart()
{
savedata();
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
loaddata();
}
public void savedata()
{
PlayerPrefs.SetInt("coinamount", ct.coinAmount);
PlayerPrefs.SetInt("losecounter", LoseCounter);
PlayerPrefs.Save();
}
public void loaddata()
{
ct.coinAmount = PlayerPrefs.GetInt("coinamount");
LoseCounter = PlayerPrefs.GetInt("losecounter");
}
script cointext
public int coinAmount;
public Text text;
void Start()
{
text = GetComponent<Text>();
}
void Update()
{
text.text = coinAmount.ToString() + " coins";
}
make sure you are calling loaddata() in the Start() method.
once you call the "Load scene" method, the lines of code under it will not be called.
so make sure you are calling loaddata() in the Start method or OnEnable.
hope that helps.
I second what Muhammad Ellawie said about loading data in the Start() method.
but as a general rule, those game data should generally not be a part of the scene, you may want to implement a singleton pattern for example so they wouldn't be part of the scene.
The easiest way is to tell unity to not destroy your game-manager: Call DontDestroyOnLoad(this.gameObject) in the Awake of the monobehaviour to keep it alive after scene reload.
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

How to code an UI button(with Exit funtion) for an Android device in Unity 3D(C#)?

I am a beginner of Unity 3D. I am writing an android app, and my start menu has an exit button. My idea is just very simple: after users press the exit button, the application will close.
I know Application.Quit() for quiting an app. But I just dont know how to detect a touch from user on a button and return the application.quit() method. Should I use sth like button.onclick or input.getTouch?
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ExitButton : MonoBehaviour {
public Button exitButton;
void Start()
{
Button btn = exitButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
Application.Quit ();
Debug.Log("You touched this button.");
}
}
After I tried to play my app, I get this error:
NullReferenceException: Object reference not set to an instance of an object
ExitButton.Start()
And it seems that I cant get signal from user touching the button.
Can someone give me a help?
I have linked my button in inspector, but i am not able to find my function name:TaskOnClick()
Inspector
Put the following code into a script
public void QuitGame()
{
Application.Quit();
}
attach the script to a game object then assign the button to a method using the OnClick window at the bottom of the button component in the inspector.
Attach the game object to the OnClick and choose the QuitGame function.
Note. This will only work in the build of the game and not in the editor.
You are mixing up between two methods of using a button.
If you are following #Jack Foulkes's method then you don't need to assign the button externally. That means you don't need the following code:
public Button exitButton;
void Start()
{
Button btn = exitButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
If you use the above code, then you don't need to add OnClick event listener in inspector, as you are already adding it inside your code. Only your code will work. You are getting the null reference, because you haven't assigned the exitButton from inspector actually.
It should look like this in the inspector:
inspector
simple you have problem with access modifiers to fix this just type
public void TaskOnClick()
{
Application.Quit ();
}
check this video it's will help you create a professional gui.
How to make a professional GUI using unity
Create a script with the following contents and then attach it to the corresponding button click
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExitButton : MonoBehaviour {
public void ExitGame()
{
print("Exiting...");
Application.Quit();
}
}
Hello,
All you need to do is to just make this function Public
like this:
public void TaskOnClick()
{
Application.Quit();
}
You Can Also make an if statement to make it much better :)
FOR EXAMPLE:
public void TaskOnClick()
{
if (Input.GetKeyDown(KeyCode.Escape) // You Can also change the key
{
Application.Quit();
}
}
And If you want to make it less effort MAKE a Function
TRY THIS:
public void ExitFunction()
{
if (Input.GetKeyDown(KeyCode.Escape) // Or Any Other Key
{
Application.Quit();
Debug.Log("exitgame");
}
}
Public void TaskOnClick()
{
ExitFunction();
}
And Also Here is the code if you want to make the same function but on the left Mouse Button Click
public void ExitFunction()
{
if (Input.GetMouseButtonDown(0))
{
Application.Quit();
Debug.Log("exitgame");
}
}
public void TaskOnClick()
{
ExitFunction();
}
If you want it with the Right Mouse Button
Here is the Answer:
public void ExitFunction()
{
if (Input.GetMouseButtonDown(1))
{
Application.Quit();
Debug.Log("quitgame");
}
}
public void TaskOnClick()
{
ExitFunction();
}
If you want it but with the middle buttonHere is the Answer:
public void ExitFunction()
{
if (Input.GetMouseButtonDown(2))
{
Application.Quit();
Debug.Log("quitgame");
}
}
public void TaskOnClick()
{
ExitFunction();
}
Full Best Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ExitButton : MonoBehaviour
{
public void ExitFunction()
{
if (Input.GetMouseButtonDown(0))
{
Application.Quit();
Debug.Log("quitgame");
}
}
public void TaskOnClick()
{
ExitFunction();
}
}
Lesson Summary:
-- Sometimes Use public when we need it like when we use GameObjects and Transforms for example.
-- if () statement is used to make the I.D.E understands the very specific objects like Do an action when .... is pressed.
Thank you.
Hope This Helped
Eyad ,
A Professional Game Developer & Front End Web Developer
Do you link your button in inspector?
EDIT.
I think this should be changed also:
void TaskOnClick()
{
Debug.Log("You touched this button.");
Application.Quit ();
}

unity 5 preferbs ui not showing when click on object

i have a a problem to active UI from prefabs when click on object using OnMouseDown code
public class TreeManager : MonoBehaviour {
public GameObject FuncUI;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown()
{
if (FuncUI.activeInHierarchy == false)
{
FuncUI.SetActive (true);
}
else
{
FuncUI.SetActive (false);
}
}
public void ExitOn()
{
Application.Quit ();
}
}
this OnMouseDown code is working if both object and gameobject UI is on hierarchy. but it not work if both i use from prefabs.. what i need to change so i can make it work for prefabs? my function UI is from canvas. when i click on the object, the FuncUI will appear on screen. this code i put inside the object that i want to click to appear FuncUI

Canvas to Canvas (MainMenu to Options) Same Scene Unity

I want my OptionButton from MainMenu to Hide the MainMenuCanvas so I can use the OptionCanvas, is it Possible?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Director : MonoBehaviour {
private GameObject mainMenu, options;
void Awake (){
mainMenu = GameObject.Find ("MainMenuCanvas");
options = GameObject.Find ("OptionCanvas");
}
void Start () {
mainMenu.SetActive (true);
options.SetActive (false);
}
void Update () {
//should i put If.else here?
/* like
if (button.clicked){
mainMenu.SetActive (false);
options.SetActive (true);*/
}
}
}
It should be possible. Though I'd recommend using Canvas.enabled(https://docs.unity3d.com/ScriptReference/Behaviour-enabled.html) variable for consistency.
Just create a function in a script to handle the click. f.e.
void onOptionsClick(){
if(mainMenuCanvas.enabled){
mainMenuCanvas = false;
optionCanvas = true;
}
else{
mainMenuCanvas = true;
optionCanvas = false;
}
}
This function should do what you want. Then you simply select the button and choose this function as a onClick() of that button in the Inspector.
Let me know if that works as I cannot test it atm!
You simply need to register your OptionButton event to a function. When that Button is clicked, the registered function will be called. Button.onClick.AddListener is used to register the Button event. Button.onClick.RemoveAllListeners is used to un-register the Button event.
private GameObject mainMenu, options;
public Button OptionButton;
void Awake()
{
mainMenu = GameObject.Find("MainMenuCanvas");
options = GameObject.Find("OptionCanvas");
}
void Start()
{
mainMenu.SetActive(true);
options.SetActive(false);
}
void OnEnable()
{
//Register Button Event
OptionButton.onClick.AddListener(() => OptionButtonCallBack());
}
//Will be called when OptionButton is clicked
private void OptionButtonCallBack()
{
mainMenu.SetActive(false);
options.SetActive(true);
}
void OnDisable()
{
//Un-Register Button Event
OptionButton.onClick.RemoveAllListeners();
}
You can find complete step to setup your UI here.

Unity Change Scene with button

I've been having problems with my code for unity. I'm using C Sharp and Unity 5.0.2f Personal Edition. Here's my code:
using UnityEngine;
using System.Collections;
public class ButtonEvent : MonoBehaviour {
public void LoadScene(int SceneToChangeTo){
Application.LoadLevel (SceneToChangeTo);
}
}
This should change the to an integer scene but when I go to the button.onclick() in the inspector and add the script nothing comes up about changing scene (Note: The script is under "_Manager" (An empty GameObject))
Add a listener for your button and make sure you put a value in numberOfLevel variable and assign your button to MyButton in the inspector or you will get a null reference exception
[SerializeField] private Button MyButton = null; // assign in the editor
public int numberoflevel;
void Start() { MyButton.onClick.AddListener(() => { changeScene(numberoflevel);});
}
public void LoadScene(int SceneToChangeTo){
Application.LoadLevel (SceneToChangeTo);
}
use this code:
using UnityEngine.SceneManagement;
///***///
public void LoadGameLevel(int SceneToChangeTo)
{ SceneManager.LoadScene(SceneToChangeTo);
}
//or
public void LoadGameLevel(string SceneName)
{ SceneManager.LoadScene(SceneName);
}
note: Worked in OnMouseDown() and Unity Ui and other

Categories

Resources