Im making my first 2D game in unity and I have successfully made it. However I want a start button.I have looked up videos on how to make a start button and they all seem to have a start button on a different screen and once clicked it goes to another scene. Where as I would like my button to be on the same screen as my game and once clicked it starts the game, while having the button disappear. Can the code also be in c# thank you.
If you don't want to have different scenes (which, by the way, it's the recommended pattern) you can pause the game until the player presses the button. More informations can be found here.
using UnityEngine;
using UnityEngine.UI;
class GameManager: MonoBehaviour
{
public Button startButton;
private void Awake()
{
Time.timeScale = 0f;
}
private void OnEnable()
{
startButton.onClick.AddListener(StartGame);
}
private void OnDisable()
{
startButton.onClick.RemoveListener(StartGame);
}
private void StartGame()
{
Time.timeScale = 1f;
// Hides the button
startButton.gameObject.SetActive(false);
}
}
Put your button on your main scene that's it.
Related
I have a problem in my project. I created an animation to open the door and made it open whenever a button was pressed. Then I copied the animation and entered its value -1 to make the door close after 2 seconds, but if the character presses the door open button again while playing the closing animation, it plays that animation and this causes a bug in the game. I apologize for telling a little complicated. I am waiting for your answers. Here is my code ->
public Text text;
public Animator anim;
private void Start()
{
text.enabled = false;
anim = GetComponent<Animator>();
}
private void Update()
{
if(text.enabled && Input.GetKeyDown(KeyCode.E))
{
anim.Play("DoorOpen");
}
}
private void OnTriggerExit(Collider other)
{
text.enabled = false;
}
private void OnTriggerEnter(Collider other)
{
text.enabled = true;
}
}
You shouldn't use the Animator Play() method and instead create parameters like a Trigger that.. well... triggers the animation.
Also, you don't say what's the error you're getting so it is hard to help you, but I guess the animation is restarting? You can set so the animations can't be transitioned to itself, so it won't restart if triggered again before finishing. Edit your AnimatorController asset, and click on the animation that shouldn't transition to itself, then uncheck where it says precisely that: "Can transition to itself". (Maybe you have to double click it, maybe you have to click on the transition, don't really remember right now, you'll figure it out :) ).
I'm developing a 2D mobile game where the player should tap on the screen to go up. I just added a pause button recently and I've noticed that when I click the button it counts as a tap on the screen, so the player goes up. Basically, in the same exact moment that I press the pause button, the player jumps and then the game freezes while he is in mid-air. Is there a way I could make so the button wouldn't count as a tap?
Here's the part of the player script that makes him move:
if (Input.GetMouseButtonDown (0) && isDead == false && isKnifeDead == false && UiStartScript.uiInstance.firstClickUi == true) {
rb.velocity = Vector2.up * velocity;
}
Heres's the part of the UI script for the pause button:
public void PauseGame()
{
Time.timeScale = 0;
}
My EventSystem:
EventSystem
My Button:
Button
An easy with no code required is to remove the code about detecting tap on screen and instead place a button that covers the whole screen (invisible button).
That button event would trigger the screen movement.
You can add extra buttons on top and Unity will automatically discard the tap from any other button below.
This way you can start adding UI all over without checking in code which should be considered.
In U. I script add
public GameObject PlayerConrtollerScript;
In your U.I Script, under the class Pausgame()
Add this code.
GameObject.PlayerControllerScript.SetActive = false;
When unpaused you need to add to your script that has the
Time. timeScale =1;
Add this code.
GameObject.PlayerControllerScript.SetActive = true;
After you have added the code mentioned above. Don't forget to add the player game object from your hierarchy into the Inspector with the U. I script, the space will be available to add a game object when you scroll down to your U. I script.
That will stop your player from moving around during pause.
This is the approach that I been done. I create a cople of tricks using Event System and Canvas for take advantage of the Mouse Input, you don't need the use of Updates functions for do the basic gameplay.
Here's my example project: TapAndJump on Github
Check the GameObjects called "Click Panel" and "Pause Button" and
respective linked methods.
JumpWithTap.cs
using UnityEngine;
public class JumpWithTap : MonoBehaviour
{
[SerializeField] private UIHandler uiHandler;
[SerializeField] private float jumpPower = 5f;
private Rigidbody2D rb2D;
private int counter;
#region Class Logic
public void Jump()
{
rb2D.velocity = Vector2.up * jumpPower;
uiHandler.SetNumberToCounter(++counter);
}
#endregion
#region MonoBehaviour API
private void Awake()
{
rb2D = GetComponent<Rigidbody2D>();
}
#endregion
}
UIHandler.cs
using UnityEngine;
using UnityEngine.UI;
public class UIHandler : MonoBehaviour
{
[SerializeField] private Text counterText;
[SerializeField] private Text pauseText;
[SerializeField] private Image clickPanel;
private bool isPaused = false;
public bool IsPaused
{
get { return isPaused; }
set
{
pauseText.gameObject.SetActive(value);
isPaused = value;
}
}
#region Class Logic
public void SetNumberToCounter(int number) => counterText.text = number.ToString();
public void DisableClickPanel() => clickPanel.raycastTarget = !clickPanel.raycastTarget;
public void PauseGame()
{
IsPaused = !IsPaused;
DisableClickPanel();
// Time.timeScale = IsPaused == true ? 0 : 1; // If you want keep the Physics (ball fall) don't stop the time.
}
#endregion
}
I guided by your code example and so on; be free that modify and request any issue.
I'm trying to create a Unity 2018 1.4f1 project that will play a specific animation when a specific key is pressed and will play a copy of the animation if the same key is pressed while the first instance is still playing.
The idea is that the user can type a word and for every letter they input an animation is played to represent that letter.
I've tried using things like Animation.PlayQueued to queue up animations but to no success.
Here's what my basic code looks like (this is only trying to play an animation on a key press):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimateKey : MonoBehaviour
{
public Animator animator;
// Use this for initialization
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("1"))
{
animator.Play("Take1");
}
}
}
Any help would be greatly appreciated.
From this thread
You can check if an Animator already is in a certain state using GetCurrentAnimatorStateInfo and only make the call if IsName returns false:
if (!animator.GetCurrentAnimatorStateInfo(0).IsName("Take1"))
{
animator.Play("Take1");
}
Note: The parameter of GetCurrentAnimatorStateInfo is the layer index. So when you work with multiple layers you'll have to adopt that.
For multiple parallel Animations however you might want to checkout the Animation component maybe.
There you don't have to handle States but rather can simply start and stop AnimationClips. You would than do
public Animation animation;
private void Awake()
{
animation = GetComponent<Animation>();
}
private void Update()
{
if(!Input.GetKeyDown("1")) return;
if(animation.IsPlaying("Take1")) return;
animation.Play("Take1");
}
I'm creating a project using the Gear VR, where you can rotate an object and display information based on the swipe and tap controls on the side of the headset.
Everything works great, I can rotate and select stuff when I use the touchpad on the side of the Gear VR, but when I change scenes and return to the main menu, and then go back into the scene I was just on, the functionality stops working.
I am using this script I've made:
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System;
public class GearVRTouchpad : MonoBehaviour
{
public GameObject heart;
public float speed;
Rigidbody heartRb;
void Start ()
{
OVRTouchpad.Create();
OVRTouchpad.TouchHandler += Touchpad;
heartRb = heart.GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
SceneManager.LoadScene("Main Menu");
}
}
void Touchpad(object sender, EventArgs e)
{
var touches = (OVRTouchpad.TouchArgs)e;
switch (touches.TouchType)
{
case OVRTouchpad.TouchEvent.SingleTap:
// Do some stuff
break;
case OVRTouchpad.TouchEvent.Up:
// Do some stuff
break;
//etc for other directions
}
}
}
I've noticed that when I start my game, an OVRTouchpadHelper is created. I don't know if that has anything to do with my problem.
The error I am getting is:
MissingReferenceException: The object of type 'GearVRTouchpad' has
been destroyed but you are still trying to access it. Your script
should either check if it is null or you should not destroy the
object.
BUT I have not referenced this script anywhere else.
When I check my scene in play mode, the script is still there with the variable assignments still present.
Any help would be great!
OVRTouchpad.TouchHandler is a static EventHandler (so it will persist through the lifetime of the game). Your script is subscribing to it when it's created but isn't unsubscribing when it's destroyed. When you reload the scene the old subscription is still in the event but the old GearVRTouchpad instance is gone. This will result in the MissingReferenceException next time the TouchHandler event fires. Add this to your class:
void OnDestroy() {
OVRTouchpad.TouchHandler -= Touchpad;
}
Now, whenever a GameObject with the GearVRTouchpad behaviour is destroyed, the static event in OVRTouchpad will no longer have a reference to it.
I have been having difficulty getting my movie to start playing once a certain button is hit. I can get it to work with void Start() but then the video starts playing as soon as the scene is loaded which I don't want. I have tried this for when the button is pressed to start playing the movie.
public MovieTexture myMovie;
public RawImage myLayer;
private new AudioSource audio;
public void onClick()
{
GetComponent<RawImage>().texture = myMovie as MovieTexture;
audio = GetComponent<AudioSource> ();
audio.clip = myMovie.audioClip;
myMovie.Play ();
audio.Play ();
}
The movie will show but not actually play. I'm sure I'm missing something obvious but as I am a noob at coding I can't figure out what it is. Any help would be greatly appreciated!
Make a custom method which will contain
void Play()
{
myMovie.Play ();
audio.Play ();
}
and assign it to the button component in the inspector
EDIT:
I meant, don't use onClick as you use Start etc, it's not executable like that. There are 2 ways:
1) You make a custom method (called whetever you want) e.g as I listed above and assign it to the onClick field in the inspector, press +, add a script and select a method from that script;
2)
public Button yourButton;
void Start () {
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){
Debug.Log ("You have clicked the button!");
}
like in the reference: docs.unity3d.com/ScriptReference/UI.Button-onClick.html
You can add a Video Player using Create -> Video -> Video Player
Set video player video clip, Render Mode as Camera Far Plane and Select camera as Main Camera
Create script as given below. Just call the playMovie() method in any button event