I've been studying c sharp as part of my games course and my teacher has left and they cant find a replacement so I'm really struggling with coding my demo game. I’ve got a problem with my doors in my game and I was wondering if anyone knew how u can get it to work because I haven’t really got a clue when it comes to coding. Basically what I’ve got is my doors are shut then when I start my game they open and then shut but I need a code that will make sure it says shut until I’m in the trigger point but all the YouTube clips haven't been working and it says it’s got problems with it. I know what I want it to do I just don’t know how to put that into action.
This is my code but I don't think it does anything:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorAnimation: MonoBehaviour
{
Animator animator;
int isOpeningHash;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
animator = GetComponent<Animator>();
isOpeningHash = Animator.StringToHash("isOpening");
bool isOpening = animator.GetBool(isOpeningHash);
bool OpenPressed = Input.GetKey("e");
bool CloseDoor = Input.GetKey("left shift");
if (!isOpening && OpenPressed)
{
animator.SetBool(isOpeningHash, true);
}
if (isOpening && OpenPressed)
{
animator.SetBool(isOpeningHash, false);
}
}
}
First of all, make 2 animations(and turn off the loop or it will loop for eternity) for the opening and closing of door. Don't make Bools for the animator. It's basically useless. At the top of a script declare a bool called as open and set it equal to false(if the door is closed from start). Check if E is pressed and open is set to false(the door is closed), play the opening animation, set open to true and if left shift is pressed and open is set to true(the door is open) play the closing animation, set open to false. You can play animations if a certain key is pressed like this https://answers.unity.com/questions/1362883/how-to-make-an-animation-play-on-keypress-unity-ga.html
This should do your job :)
Related
I'm trying to start a couroutine that triggers an animation then waits for 10 seconds and goes into another anim.
I have a simple IEnumerator that goes between 2 anim stages and has a small wait between each one.
When I run the scripts the first time it does wait 10 seconds to start (trapActivate) and then waits 10 seconds to start (trapInactivate) but the animations after that just play one after another without waiting the 10 seconds they should be waiting between anim states.
Not sure what the issue could be.
I looked up a a lot of threads of people having issues because they where starting their couritne inside their Update function but I'm not doing that so not really sure what else could be causing that.
I already tried changing the wait time and no matter how long they are after the first wait they just start playing one after another.
I can see them jumping between each other in the animator
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimateEveryNTime : MonoBehaviour
{
private Animator animator;
public void Start() {
StartCoroutine(playAnimation());
Debug.Log("Couroutine");
animator = GetComponent<Animator>();
}
public IEnumerator playAnimation() {
yield return new WaitForSeconds(10f);
// Insert your Play Animations here
animator.SetTrigger("trapActivate");
yield return new WaitForSeconds(10f);
animator.SetTrigger("trapInactive");
}
}
Here is a pic of my animator layout:
enter image description here
Your image shows the type of the two parameters is Bool not Trigger. The interest thing is SetTrigger can also work for Bool parameters and set their values to true. So you need delete them and create new parameters with the type Trigger and same names.
I'm a beginner and this is my first post here so please let me know if I could do anything better.
Using PUN 2 in Unity, I'm trying to return a connection error message when the user attempts to connect to a Photon server but fails.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; //Library that provides utilities for scene management
using Photon.Pun; //Library for Photon, provides networking utilities
using Photon.Realtime; //Helps solve problems relating to matchmaking and fast communication
using UnityEngine.UI; //
public class MenuMan : MonoBehaviourPunCallbacks
{
public override void OnDisconnected(DisconnectCause cause) //Callback for when device fails to connect to server. Parameter 'cause' is the cause of this failure
{
Debug.Log("failed :("); // FOR DEBUGGING
Debug.Log(cause); //Prints in the console the cause of this connection failure
DisplayErrorMessage();
}
public Text Message;
public string MessageValue = " ";
public void DisplayErrorMessage() //Method that displays a connection error message to the user
{
SceneManager.LoadScene("Character Select Menu"); //Ensures user is on the Character Select menu
MessageValue = "AAAAAAA";
//Message.text = MessageValue;
Debug.Log(Message.text);
Debug.Log(MessageValue);
}
}
When I run this code, the text "AAAAA" flashes for a second, then disappears. Through testing I found out this is because the message displays first for some reason, and only after does the scene change thus resetting the text.
I tried using coroutines to delay MessageValue from being altered until the scene changed:
public override void OnDisconnected(DisconnectCause cause) //Callback for when device fails to connect to server. Parameter 'cause' is the cause of this failure
{
StartCoroutine(GoToCSM());
DisplayErrorMessage();
}
IEnumerator GoToCSM()
{
Debug.Log("cor started");
SceneManager.LoadScene("Character Select Menu")
yield return new WaitForSeconds(3);
DisplayErrorMessage();
Debug.Log("Done");
}
public Text Message; //Initialises a 'Text' type object, which will be set to the Connection fail message
static string MessageValue = " "; //Initialises a string which will be written to the 'text' component of the above object
public void DisplayErrorMessage() //Method that displays a connection error message to the user
{
MessageValue = "AAAAAAA"; //Writes the string to be displayed to MessageValue
Message.text = MessageValue; //Sets the above text to the 'text' component of the Message object, thus displaying it on the screen
}
However the coroutine never goes past the yield statement. It just stops at the yield statement and doesn't continue (even the Debug.Log("Done") doesn't get logged).
But when I tried switching some things round and put SceneManager.LoadScene("Character Select Menu") beneath the yield statement, that was executed just fine, as well as the debug statement below. I have no idea why this could be, and am very confused.
This was meant to be an extremely simple 10 minute task and I've wasted days trying to figure out what to do now. Any help would be extremely greatly appreciated. Thank you!
When switching scenes the object running the coroutines gets destroyed. Which results in it never executing the delayed code in the coroutines, this also applies when loading the same scene as you have currently loaded.
Unity reloads the whole scene, it resets everything!
This is also the reason why you see the text flashing for a few seconds. You set the text of some component in your scene, then unity reloads it and its reset.
SceneManager.LoadScene is not instant it just tells unity to start loading the Scene and then switching to it when ready.
Which by the way is not a very performant thing to do and should only be done when you need to really reset it.
If you want to pass values such as cause of disconnection from one scene to another you should use static variables.
These are not stored in objects(that get deleted on scene load). They are static and get saved when switching scenes.
It would help if you shared some more details about the structure of your project. That can help us find a solution that suits your needs.
I am trying to display player tutorial when the user 1st starts the game using playerpref and want the game to be paused, the problem i am facing is that Time.timescale=0 is not pausing the game when placed inside start (tutorialCanvas gets displayed), but works when is called by a button(Pause button).
Following is the code I use
void Start()
{
if (PlayerPrefs.HasKey ("test4") ==false ) {
tutorialCanvas.SetActive (true);
Time.timeScale = 0;
}
}
Time.timeScale = 0 is really messed up for me so what i could recommend you is that if you just want to pause something like pausing a movement of a character then you can try it like this :
GameObject PlayerScript;
if(Input.GetKey(KeyCode.P)){
//lets disable the playermovement script only not the whole object
PlayerScript = GetComponent<PlayerMovement>().enabled = false;
}
I've been stucked there also so i made an alternative way. And you can also visit this one. If you want a free of that asset you can get it here
I had this issue recently, although it was only doing it on a build, and not in the editor. Changing timeScale to something like 0.0001f would fix it, but that wasn't a great solution. Creating an input settings asset (under Camera -> Player Input -> Open Input Settings) seemed to have fixed it for the builds.
Hey guys I've been working on a 2D terraria-like game, from a tutorial I found on Youtube. I've been using Quads as blocks. The link to the series is:
https://www.youtube.com/watch?v=KONw5GX0Ixs
The only difference is I've been in a 2D project rather than a 3D. I'm trying to implement a mining system, but the clicks aren't detected much less the blocks that I'm clicking on. The system doesn't even detect the clicking, much less the blocks I'm clicking on. I'm new to coding so I'm not sure how to fix this, anything helps, thanks.
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mining : MonoBehaviour {
public Vector2 direction;
void Update() {
if (Input.GetMouseButtonDown (0)) {
Vector3 c = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit2D = Physics2D.Raycast(this.gameObject.transform.position, direction);
Debug.Log ("hello");
if (hit2D.collider.gameObject != null) {
Debug.Log (hit2D.collider.gameObject);
Destroy (hit2D.collider.gameObject);
}
}
}
}
First of all, change
Input.GetMouseButtonDown(0)
to
Input.GetMouseButton(0)
as its
Returns whether the given mouse button is held down.
tell me if that fix your problem. If not, I will try to figure sth out:)
I am creating game and I need to track some statistics. I want to track total played time (since the user started game and till the moment he definitely ended game).
I have a "continue" option from main menu, so if someone turned game off and then started it and selected "Continue" - it means that I need to increment the old playedTime because, it is not new player.
How can I track this total played time? I cannot use Editor Scripts because I need this to be available just from the game build (player will start game with .exe, not from Unity)
You can store the realtimeSinceStartup on an ApplicationQuit, for example in the playerprefs. Something like this should do the trick:
using UnityEngine;
public class TimeStatistics : MonoBehaviour
{
public float TotalTime
{
get
{
float totalTime = Time.realtimeSinceStartup;
if(PlayerPrefs.HasKey("totaltime"))
totalTime += PlayerPrefs.GetFloat("totaltime");
return totalTime;
}
}
void OnApplicationQuit()
{
PlayerPregs.SetFloat("totaltime", this.TotalTime);
}
}
Make sure the script always exists, otherwise you wont get an OnApplicationQuit!