Quit Application on Escape button pressed - c#

I'm currently making a simple 2D Pong game in Unity for a school project, and I have this code attached to my camera so that when the exit key is pressed it will close it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EscapeScript : MonoBehaviour
{
void Update()
{
if (Input.GetKey("escape"))
{
Application.Quit();
}
}
}
However whenever I'm in it, pressing Escape does absolutely nothing. I have tried variations such as "GetKeyDown" and "KeyCode.Escape" but they don't seem to work either

Never mind, I figured it out. It was because I was in the editor, and Application.Quit() doesn't work while in the editor. I needed to use UnityEditor.EditorApplication.isPlaying = false;

Related

How can I change scene by pressing a key in unity

Now I working on project like black mirror banderanatch. I create a movie that player has to interact with by pressing a specific key on keyboard to change to another scene. I dont know how to code it, I don't need a box or anything to click because in video I will say what button to press to go on another scene. I've tried put the video in UI in each scene but its does not work
some of the code I'm using
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeSceneWithButton : MonoBehaviour
{
public void LoadScene(string sceneName1)
{
SceneManager.LoadScene(sceneName1);
}
if{keyboard.write() a;
LoadScene(sceneName1)}
}
what should I add to make it change scene with specific button
ps.first time using unity any advice please teach me
You need to check the input in the Update function, like this:
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeSceneWithButton : MonoBehaviour
{
[SerializeField] private string _sceneName;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene(_sceneName);
}
}

OnCollisionEnter2D is not being called

I'm fairly new to Unity and I've decided to work on a simple 2d platformer from youtube tutorials.
Everything works fine until I start using collisions. My problem isn't only that it doesn't work, It's that it doesn't appear at all on auto-complete.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class finishLine : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
private void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.CompareTag("Player")) {
SceneManager.LoadScene("level2");
}
}
}
I've also added rigid bodies and box colliders to both objects (player and finish line).
Anyone know what's wrong?
Make sure that you used BoxCollider2D and not the 3D one.
If the autocomplete doesn't work try restarting VisualStudio or whatever IDE you use. If that doesn't work look in the Unity Settings under External Tools and try regenerating project files. That works for me sometimes.
So a couple things you might want to look into to fix this are:
Check if you have the right colliders on both your gameobjects (in this exmaple box collider 2D I assume)
Check if either of your colliders has the "Is Trigger" box check or not. If yes then uncheck it
Make sure your player gameobject has the "Player" tag and the same as the tag you compare in your script because compare tag is case sentitive
Check if you have your finishLine script on the object you want as the root object meaning it's the parent of all the other one inside it and has no parent (this doesn't need to be the case all the time but in this scenario it might help fix the problem)
Did you check the trigger box in the colliders?
Does any one of those objects have a rigid body?
Did you have other functions that destroyed the character when it reaches the destination that is meant to be the trigger?
You can try to set up a two new cubes for testing purposes to narrow down the problem.

Unity Scene is not loading

I have a button in my Unity2D game that the user can click and the scene will start over. On my button, I have a script attached with this code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Restart : MonoBehaviour
{
public void PlayAgain()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Debug.Log("Play Again Works");
}
}
I know that the button is working and the Play Again function is working because the Debug.Log is working. However, when I click the button the scene doesn't restart. When I click the button, in the Unity hierarchy, next to the scene name it very briefly shows "(not loaded)". My scene is showing up in the Build settings. Does anyone know what could be causing this? Thanks for your help.
First check that you have added the scene in your build settings. If that is not your problem try following code.
SceneManager.LoadScene (SceneManager.GetActiveScene().name);

How can I make another scene after scanning the image target

Good day everyone,
how can I make another scene after scanning the image target? So far I can only do the buttons which are the basics and am currently working with c#, visual studio, unity and vuforia.Iv'e done the main menu screen which has the buttons scan and exit. Whenever you click the scan button it will automatically go to the AR camera and my question is how can I make a AR camera which you can scan an image and go to the another scene. No animation or whatsoever, just scan the image and go to another scene. Does someone has an idea of how to make it happen?
so far this is what iv'e coded:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour {
public void System()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1);
}
public void Back()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex -1);
}
public void Exit()
{
Debug.Log("You have exited the app");
Application.Quit();
}
}
In your case you can just create a gameobject as a child of your image target, attach a script, lets say sceneloader.cs and put in the start() method your load-scene-code....but this are total basics. Did you even read the documentation how image targets work?

How do I get touch working in Unity3D?

I'm making an Android app with Unity3D and it works with click detection already, but not with touch. I need touch though for multitouch detection.
What I want: I have my player and 2 images of arrows. One arrow points right and one left. When I touch the left arrow the player should start moving left, when I touch the right arrow the player should start moving right.
But how do I detect which arrow is touched (and held)? All the code I found on Google is too old and not working anymore.
I'm working with C# scripts and it's a 2D game.
Klausar, what you're looking for is .........
A BUTTON (!!!)
it's that easy!
click "add Canvas". (You very likely want "scale to screen size" - select that option.)
click "add Button".
there is no "three" .. go drinking.
In your code, have a routine like this for the right-side button
public void UserClickedRight()
{
Debug.Log("click right whoo!");
}
and have a similar routine for the left-side button.
1. Go to your Button in the editor.
2. Simply drag the script to it and select UserClickedRight !!
You actually do not have to program buttons from scratch :)
This is a basic mechanism of Unity - drag a game object to a "slot" for it in the Editor.
(The game object you drag, has the script in question on it.)
You DO NOT need to go to the level of touch handling to achieve a button!
Now you ask, what about "when holding down on the button"?
It's very easy, you just need to know a couple of things about the Unity "event" system.
In Button, Unity have done all the work for "OnClick":
Since "click" is common, they put that one right in the Inspector panel for you for convenience.
The good news is that Button has many more events you can use.
http://docs.unity3d.com/ScriptReference/UI.Button.html
My guess is you want to use OnPointerDown and OnPointerUp in your case.
To use the other events (which Unity did not bother putting in the Inspector panel) is very simple, you just
1, make a script that references the events you want,
and,
2, you put that script ON the button in question ...
it's that easy.
Step by step explanation:
You're going to be using Unity's event system, so:
using UnityEngine.EventSystems;
Next. You know that a script normally starts like this...
public class FancyButton:MonoBehaviour
The "MonoBehaviour" part just means that it's a c# script which will be "driving a GameObject".
In this case we have to further alert the engine that you will be using those click events. So you add this.
,IPointerDownHandler,IPointerUpHandler
So far we have this
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
Now the easy part.
You just type the two routines which Unity will run for you, when, those things happen.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
public void OnPointerDown(PointerEventData data)
{
Debug.Log("holy! someone put the pointer down!")
}
public void OnPointerUp(PointerEventData data)
{
Debug.Log("whoa! someone let go!")
}
}
Now all you have to do is drop that script on the Button. Done!
You can put that script on any button, where, you need that functionality.
Next, click on Obi-wan to see where we're at so far!
Finally, it sounds like you want to do something "when the button is being held down". That's just a general programming issue - you'd have a boolean which you turn on and off as the button goes up and down. Let's do it.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
[System.NonSerialized] public bool mouseIsDownRightNow;
public void OnPointerDown(PointerEventData data)
{
mouseIsDownRightNow = true;
}
public void OnPointerUp(PointerEventData data)
{
mouseIsDownRightNow = false;
}
}
You could access that variable from another script, or whatever you want.
Add the following if you want to run a routine while the button is down:
void Update()
{
if (buttonIsDownRightNow) WhileButtonIsDown();
}
private void WhileButtonIsDown()
{
Debug.Log("THE BUTTON IS DOWN! WHOA!");
}
Try that and watch the console as you hold the button down and up.
Here's an example of something like continually increasing a value while the button is down:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
[System.NonSerialized] public bool buttonIsDownRightNow;
private int countSomething;
public void OnPointerDown(PointerEventData data)
{
buttonIsDownRightNow = true;
}
public void OnPointerUp(PointerEventData data)
{
buttonIsDownRightNow = false;
}
private void WhileButtonIsDown()
{
++countSomething;
}
void Update()
{
if (buttonIsDownRightNow) WhileButtonIsDown();
Debug.Log("value is now " +countSomething.ToString());
}
}
That's all there is to it. Once you really understand events in Unity, there is not much more to learn about Unity.
The only other important topics are Mecanim, shader writing, touch, coroutines, threading, PhysX, native plugins, sprites, networking, dynamic mesh, navigation, VR, AR, animation, inverse kinematics, particles, terrain, IAP, lighting, baking, shadows, MMP, character controllers, and audio. Enjoy!
You should firsty read this.
What you are trying to do is actually simple:
foreach (Touch touch in Input.touches) {
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
if (guiTexture1.HitTest(touch.position)) {
// Maybe move left
}
if (guiTexture2.HitTest(touch.position)) {
// Maybe move right
}
}
}
Edit 1: this code now checks which image is being pressed
Edit 2: Added multitouch support

Categories

Resources