I'm makimg a game in Unity using C# developed for Android. I'm testing using Unity Remote 4. I was just wondering if a sprite can be used as a button in Unity rather than the button made in Component -> UI -> Button.
I've tried this:
private void Update()
{
if (Input.touchCount > 0)
Application.LoadLevel("startScene");
}
Which does work. The button is being used to switch from the main menu to an options menu.
Ideally, I want the button to be in the same place in the options menu to be used to go back to the main menu. The problem then is that because the scenes switch instantly, the scenes switch between each other over and over I guess because the next scene gets the touch input as well.
How can I delay the time between the scenes switching, or is there a better way to use sprites as a button??
You can create a menu system which is persistent in scenes. Have a look at This Tutorial Video for guide
Usually buttons perform their function once a tap has been performed. A tap is a press and release on the button. What you are doing is performing your function on a press which is causing your buttons to be triggered continuously while you hold your finger.
Pseudo code:
If a finger presses on the sprite
If the same finger is release on the sprite
The button has been pressed.
You can use ray casting to detect touch on the sprite
private void Update()
{
if (Input.touchCount != 1) return;
var wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
var touchPos = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos))
{
// Your code
}
}
This is one way that has worked for me:
Add the sprite that you will use as the background of the button to the stage.
Add a Collider and mark it as a trigger.
Assign a script where you add any of the following functions depending on your case.
private void OnMouseDown () {
// Runs by pressing the button
}
private void OnMouseUp () {
// Runs when button is released
}
Related
I am new to C# and Unity and I'm trying to figure out how to make an animation for an object in unity play when I press a key but I can only make the animation play once, and then it is broken and doesn't work. (I am trying to make an FPS game)
The code I have right now looks like this:
void Start()
{
gameObject.GetComponent<Animator>().enabled = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
gameObject.GetComponent<Animator>().enabled = true;
}
}
When I press run and left click, the animation triggers and does as it is supposed to but when I try to do it again, the animation doesn't work. Can anybody help me change this code so that the animation will work and play every time the button is pressed?
I am assuming your animation is non-looping as if it was looping it would already play back into itself when it is over.
One quick note I would have with your code is do not use GetComponent in an Update function as it is quite costly. An easy way to get an animation state to reset is to enable and disable it, however I am assuming you want to have more animations than shooting. You would want to look into what is called an Animation Tree or a Blend Tree and add States to your animation. Examples of states would be an Idle, Walk, Run, Shoot, Crouch, etc. I would consider researching Animation Trees and Blend Trees to get a full animation cycle in.
Once you get a State machine working, I would have the enter go to an Idle state, then either set a transition Bool or directly switch the animation in code.
// when you serialize a private field, it will appear in
// the inspector so you can drag in the reference in the editor
[SerializeField] private Animator anim = null;
private void Start()
{
anim.enabled = false;
}
private void Update
{
if(Input.GetButtonDown("Fire1")
{
Shoot();
if(!anim.enabled)
anim.enabled;
else
anim.Play("AnimationStateName", -1, 0f);
}
}
I have not tested the code, but I believe this would work with your setup. I would still strongly advise to not do this and look into Trees. After implementing the tree, instead of calling using the enabled, just use the line anim.Play("AnimationStateName", -1, 0f) or you can do anim.SetBool(isAttacking, true) if you set your state to transition from Idle/Run/Walk/etc. to Attacking when the isAttacking bool is set to true.
I found a video that might help you out. I do not want to post a full explanation to animation states and blend trees, just point you in the right direction to a better approach.
I am coding a clicker game and I do not want my program to calculate whenever I press the UI. I have tried using OnMouseDown, OnPointerDown and !EventSystem.current.IsPointerOverGameObject() but all of them ruin the clicker-feel because you can't spam click. Are there any shorter alternatives? Thank you in advance!
Edit: I've done all the things you've commented and I've found the problem. Whenever I click my mouse button, text appears with the number of coins I get per tap. Therefore, it counts as a UI element, making it not possible to spam-click. I have now turned off the "Raycast Target" for the text and now it works as it should. Thank you for your help!
You can use Input class along with a check:
void Update()
{
// Check if the left mouse button was clicked
if (Input.GetMouseButtonDown(0))
{
// Check if the mouse was clicked over a UI element
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Clicked on the UI");
}
}
}
Or you can use OnMouseDown on specific object where you want to detect the click but with a UI check:
void OnMouseDown()
{
// Check if the mouse was clicked over a UI element
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Clicked on the UI");
}
}
I have a space ship that will rotate clockwise or counter-clockwise depending on if the left or right button is pressed. I was using a virtual joystick and it was working fine but decided to change to left and right buttons. Now if click a button it will rotate to a fix position and stop each time i press the button, I'd like for it to move continuously in one direction while button held down and stop when released.
I'm using the unity standard assets with the cross platform input ButtonHadler script in conjunction with my "move" script.
void Update()
{
if (CrossPlatformInputManager.GetButtonDown("turn"))
{
TurnShip();
}
}
public void TurnShip()
{
transform.Rotate(Vector3.up * 50f * Time.deltaTime);
}
You're using GetButtonDown, which returns true only once when you press the button, and remains false until you release the button and press it again. Use GetButton instead.
Changing to GetButton was part of what I was missing but I had also set up my buttons up incorrectly I had accidentally added one event type with two function a pointer down and pointer up in the same event type instead of separating them.
The cursor disappears when making a single click, like so:
How to reproduce:
get the Game Jam Menu template:
https://www.assetstore.unity3d.com/en/#!/content/40465
Add another scene with an FPS controller imported from the standard
assets.
Tick the "change scenes" in the UI -> start options component.
Press escape and touch the slider, any single click will make the
cursor disappear.
It looks like this: https://imgur.com/a/hefmP
If I tick off the mouse look -> lock cursor in the FPS controller then this doesn't happen, but I also see the cursor in my FPS game.
I tried to add Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; and the opposite when pausing and unpausing but it doesn't help. Probably because the MouseLook.cs is also updating them in:
I'd rather not couple the FPSController and the pause menu and they're also in different scenes.
So how else can I unlock the cursor when entering the pause menu? Is there an event pattern that can be used here?
It also darkens the scene, but that's for another question.
It's been modified by the MouseLook script which is used in the FirstPersonController script. One solution is to modify the MouseLook script but a simple Asset update would kill that modification.
A proper solution to this problem is to disable the FirstPersonController script when you open up any menu and then enable it back when you close that menu. Also, when you disable it, manually set Cursor.lockState to None and set the cursor to visible.
Below is a simple function that will handle that. Each of your menu open and close button should be linked to the function below. When you call it, pass false to it with the open button and true to it with the close button:
void enableFPS(bool enable)
{
GameObject fpsObj = GameObject.Find("FPSController");
FirstPersonController fpsScript = fpsObj.GetComponent<FirstPersonController>();
if (enable)
{
//Enable FPS script
fpsScript.enabled = true;
}
else
{
//Disable FPS script
fpsScript.enabled = false;
//Unlock Mouse and make it visible
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
I recently thought about adding a InGame Button to my Game. It's not a GUI or UI Button, it's a Block, added to a Wall for example.
Dummy Code:
OnTriggerEnter(c:Collider) {
if(c.gameObject.tag =="Player")
{
//Text = "E to interact!"
if(key.pressed("e")
{
//Connect the Button to a specific Block, play a Animation
}
}
}
So how do I connect a specific Block to the Button, and if I press e, Play the Animation just on the specific block? Please keep in mind that I'm new in Unity.
Thanks for helping out!
I don't know if you already managed to create your animation, so I-ll explain from scratch. When in the editor, select your Door and press ctrl+6 to open the animation window. From here you can animate your block. When you will be done creating the animation, your block object will have a new script attached to it: an animator. You can see the animator state machine in the animator window
These are two different things:
Animation: Defines a single animation (translation, rotation, change of color, ...)
Animator: defines when an animation occurs for the corresponding gameobject. An animator can have variables (for example, a bool) that define which is the next animation to be played
Any object can have an animator (your button can have one to move when it is pressed. You door can have another one to open / close)
For instance, in your button animator, you should have three states: Idle, Press, UnPress.
The state Press will contain the animation "press" with speed 1. The state UnPress will contain the animation "press with speed -1
Then, still in the animator window, You will create links between Idle and the two other states and add a trigger condition called "OnPress" (for example)
You can do the same to animate your door
In your Button code, you will then write
public Animator Door; // In the editor, give a reference to your door. It must have an Animator script for this to work
OnTriggerEnter(c:Collider) {
if(c.gameObject.tag =="Player")
{
//Text = "E to interact!"
if(key.pressed("e")
{
GetComponent<Animator>().SetTrigger("OnPress"); // The button's animator goes to "pressed" state
Door.SetTrigger("Open"); // The door's animator goes to "open" state
}
}
}
Then you could add another trigger to unpress the button
One more thing: When you say "Connect the button to the block", I feel like you misunderstood something: Your button script should be already added to the block in the editor
Look at these two links for more information on animations:
http://docs.unity3d.com/Manual/animeditor-UsingAnimationEditor.html
http://docs.unity3d.com/Manual/AnimatorWindow.html