Previous scene lingering in the background Unity - c#

I've been trying to switch from the main menu for our game into the first level. But the main menu keeps showing in the background no matter what I try.
So, this is our main menu (the loading screen looks just about identical, but with a loading bar in the center and without the buttons or SOMNIUM):
Yes, I know it looks ridiculous. This was a stand-in that one of our artists did in ten minutes in paint. They're still working on the real main menu art.
And this is what I get when I try to start a new game (you can see how the loading canvas from the main menu scene is still there in the background):
I got the code I'm currently using from a tutorial (I hoped copying their code would help - it didn't, but it looks nicer than mine).
public class StartGame : MonoBehaviour
{
public GameObject mainMenuCanvas;
public GameObject loadingScreenCanvas;
public Slider slider;
public void NewGame(int levelToLoad)
{
StartCoroutine(LoadAsynchronously(levelToLoad));
}
IEnumerator LoadAsynchronously(int levelToLoad)
{
// Set the loading of the level as an async operation
AsyncOperation operation = SceneManager.LoadSceneAsync(levelToLoad, LoadSceneMode.Single);
while(!operation.isDone)
{
// Get the 0-1 progress value
float progress = Mathf.Clamp01(operation.progress / 0.9f);
// Apply the progress value to the slider, which also goes from 0-1
slider.value = progress;
// Going to have a thing here to show the percentage completed as text
// End the Coroutine
yield return null;
}
}
}
Other than specifying LoadSceneMode.Single, I've trying directly destroying the main menu scene when moving to the game scene. But that had no effect. I've also trying turning off the canvas for the main menu scene when moving to the game scene. But that didn't work either.

Before loading the new scene, you can get a handle to the current scene with SceneManager.GetActiveScene. Then when the new scene has finished loading, you can manually unload the old scene with SceneManager.UnloadSceneAsync.

Related

How to make animation repeat on every keypress in unity (Unity3d, C#)

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.

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.

Strange plane behavior in Unity3D while changing scene

I am a beginner with Unity3D.
Until now I have learned a few things.
For example, create a simple 2D menu, switch from one scene to another with an appropriate C# script and associate the scripts with the objects.
The problem I pose here is about the behavior (strange to me) of the white panel behind the menu when I change the scene.
I have two scenes, the first which is the menu and a second one is the actual game.
I used UI elements to create the first one, while I used 3D objects to make the second one.
So, what happens?
It happens that when you step into the second scene by clicking on the green button the background becomes brown. If, on the other hand, I run the second scene individually without going through the first one (launching the scene directly), the background remains white.
See this short video for further details.
Why?
Listed below are some images, hoping they can help me understand my problem.
The first scene (dev mode):
The first scene (running):
The second scene (dev mode):
The second scene (running directly):
The second scene (running after clicking the green button "Comincia"):
The script I use to change the scene (linked to the green button):
using UnityEngine.SceneManagement;
using UnityEngine;
public class GameScene : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void PlayNow () {
SceneManager.LoadScene("Game", LoadSceneMode.Single);
}
}
Update: I have updated the information on the application. I added a new screenshot where you can see the camera settings. Meanwhile, I changed some things, but the problem still remains. I also noticed that this problem only happens when I switch to the Game scene, when I switch to other scenes instead it does not.
Added a new screenshot showing the inspector of the Main Camera object:
I was able to understand where the problem was: I made an improper use of the Plane object (highlighted in the screenshot). By removing it, now it shows correctly the solid color white background as set on the Main Camera.

Unity - Load options additive to the ingame scene

at first, my most important research for this topic:
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
https://docs.unity3d.com/ScriptReference/SceneManagement.LoadSceneMode.Additive.html
When I start my game from the main menu I get into the "Ingame" scene. The ingame scene got an ingame menu with some buttons. I can click an "Options" button there.
So from the main menu I start the game by this method:
public void StartGame()
{
LoadScene("Ingame", LoadSceneMode.Single); // Load the main scene of the game
}
So when I open up my ingame menu and click on the options button I call this method
public void LoadOptions()
{
LoadScene("Options", LoadSceneMode.Additive); // Don't destroy the game and load the options menu
}
This works fine, because it doesn't destroy the ingame scene. But the problem is, that all objects are kept to the options scene. That is not, what I have expected.
How can I get into the options scene without my ingame objects and get back to the ingame scene when finishing the options?
Thanks :)
Once you are done with your Options scene, you can change your active scene back to your game and unload the menu scene. It will look something like this.
Scene gameScene = SceneManager.GetSceneByName("Ingame");
SceneManager.SetActiveScene(gameScene);
SceneManager.UnloadSceneAsync("Options");

Is there a way to cancel Touches on Awake of a Screen?

I'm having an issue with a game I'm working on. As the user drags his character around the screen, if the character dies while dragging, I switch to the "dead" scene. The problem is that on the new scene there are two buttons using the new Unity UI. Buttons and if the player happens to have his finger over one of the buttons when the scene loads and lets go as a reaction they end up executing the button before they even see what was on the screen.
Is there a way I can say on Awake, Start or Enable to cancel all touches? Forcing the user to lift their finger off the screen and then tap the button they want after they digest the screen?
IMHO better user experience is to play an animation when the character dies. The animation could even be as simple as blurring or dimming the view slowly. Then the player has some time to react and he or she will quite likely end the ongoing drag.
If you still want to disable all touches, one work around could be to add boolean telling if any new touches has started at the new scene. Unfortunately, I am guessing that this will not work robustly:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
private bool newTouchesInThisScene = false;
void Update() {
for(int i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
newTouchesInThisScene = true;
}
}
}
}

Categories