Press a in game Button to play a animation - c#

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

Related

Change Player Position when a scene was change Unity

So, I have this game that I created and there's a button that whenever I clicked the button the scene will change but my problem is whenever I click the scene button change it will go back from the start of the stage. I kind of want it for example in scene 1 I already moved into the middle of the stage, so when I click the button scene change, in scene 2 my player is already in the middle of the stage just exactly in the scene 1 and not go back to the start of the level.
This is something called State-Saving. In your case, you want to save only the position of the player. In the function you're calling to change scene, save the position as in:
public static vector3 TempPosition;
TempPosition = player.transform.position;
And reassign it to the player when the scene loads.

If and ActiveSelf. Only works once. With example project

First time developer here and I am struggling with a problem.
I made a mock up of the problem in regular Unity 3d since the VR scares some talented people away from helping me. That can be downloaded here: https://gofile.io/d/qHDlUZ
File is a zip called: SoundTestTroubleShooting. A Unity build on 24.7MB
Follow the number on the buttons.
Button 1 "Choose Music" Activates the Cube.
Button 2/4 "Play Music" Checks if cube is activated and plays song if that is the case.
Button 3 "Restart Scene" Stops the music and reloads the scene.
Cube has dontdestroyonload.
After that i press button 2/4"PlayMusic" and it cant find that the cube is active.
WHY?! Going nuts here.
Old text with the entire problem here:
In my game I have four songs in the start menu that my player gets to choose from. He chooses one by pressing one of four buttons. This activates an empty GameObject, lets call it SmileMusicTrigger. SmileMusicTrigger has a dontdestroyonload and is deactivated by the other three buttons if player wants to switch song.
Player press Begin which moves him into position. He presses start and this button has:
public GameObject SmileMusicTrigger;
public GameObject EpicMusicTrigger;
public GameObject GodMusicTrigger;
public GameObject VikingMusicTrigger;
void OnTriggerEnter()
{
if (SmileMusicTrigger.activeSelf)
{
AudioManager.instance.Play("Smile");
}
if (EpicMusicTrigger.activeSelf)
{
AudioManager.instance.Play("Epic");
}
if (GodMusicTrigger.activeSelf)
{
AudioManager.instance.Play("God");
}
if (VikingMusicTrigger.activeSelf)
{
AudioManager.instance.Play("Viking");
and my game start and and the music begins fine.
When player dies he restarts the scene with restart button which has this to say about the music:
void OnTriggerEnter()
{
AudioManager.instance.Stop("Smile");
AudioManager.instance.Stop("Viking");
AudioManager.instance.Stop("God");
AudioManager.instance.Stop("Epic");
}
}
after this code has run the scene restarts and it does not seem like my Start button can check the active state of SmileMusicTrigger again. I know SmileMusicTrigger is active through the restart of the scene because I see it under dontdestroy in the hierarchy when game is running and it is checked as on in inspector. But I cant seem to call it again. Thus my music only plays once.
Audiomanager is also under Donotdestroy so I dont think the problem is there.
Sorry if this is messy. I am working really hard to get this working but I am so stuck right now.
Thankful for any help.
All the best!

How to disable GameObject after animation is finished

So I have an animation that fades into the menu screen but after the animation ends none of my buttons work. I have figured out that it is because the GameObject that holds the black image that fades to clear is always in the front, blocking me from using any of the buttons. I tried to write a script, that's attached to the game object, that disables the GameObject after it completes the animation, but it isn't working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelChanger : MonoBehaviour
{
public Animation anim;
public void SetTrigger()
{
this.StartCoroutine(this.PerformAnimRoutine());
}
private IEnumerator PerformAnimRoutine()
{
var state = anim.PlayQueued("Fade_In", QueueMode.PlayNow, PlayMode.StopSameLayer);
yield return new WaitForSeconds(state.length);
this.gameObject.SetActive(false);
}
}
Is there anything wrong with the code or is there an easier way to accomplish this? I am extremely new to unity so I am very stuck.
If all you are doing is fading a sprite to clear and you seem to know about coroutines, I might start by suggesting you do the fade within a coroutine instead.
Have that decrease the alpha by some fraction each frame and when it's 0 disable the object.
That's just if that sounds more fluid, nothing wrong with the animation way.
Doing it with animations though :
I'm not confident that you can disable the object the animation is on in that animation. If it is available on the dope sheet try that. Otherwise we can use state behaviours or animation events.
Animation Events
These can be used to trigger a function at a certain point of an animation. You can create them similar to keyframes. Here is a link to Unity's guide on this topic.
All you'd need to do is create an event and place it at the end of the animation. Then you need to in a script of that object make a public function that simply disables the object. Call that with the event.
State Behaviours
State Machine Behaviours allow you to define a script to run on a given animation state. It has many functions to hook onto such as OnStateEnter and OnStateExit.
You'd want to click on the state that fades in the animator. In the inspector you should be able to click "Add Behaviour". This will create a script that you can open and edit. Here is the reference for that class.
From there is should be very simple to disable the object through OnStateExit.

Unity Button Animation

Does anyone know a possible way for an animation that makes it so when a button gets clicked text pops up above the button that says [Clicked]. It must fade away after 3 seconds and it continues to go up. (The text will move up.)
Pretend like this is how it would look
Clicked but faded away
Clicked
Clicked
Clicked
Button
(Unity Using C#)
How about using a Prefab for this?
You'd create a Prefab with a root object and a text label as a child. Then you animate the text label upwards and fading out over three seconds using the Unity animation window.
On button click, you instantiate the prefab, make it a child of the button, and position it at the same position as your button AND auto-destroy it after 3 seconds.
Here's a code example, pretending that your prefab name is "myAnimatedText"
GameObject animatedButtonText = Instantiate(Resources.Load("myAnimatedText"), transform);
animatedButtonText.transform.position = transform.position;
Destroy(animatedButtonText, 3.0f);

Using sprite as button in Unity

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
}

Categories