Unity3D VR app: fade to another scene after a certain time - unity3d

I'm trying to develop a VR app where you can move around and interact with music (moving the audio sources, and so on). So, you can't actually die in this app, which is why a fade to black on trigger wouldn't help me. I'm trying to get a fade to black and show the credits after a certain amount of time (specifically, when the music is over). Maybe even a fade out (black) and a fade in (to another scene containing the credits) would do the trick. I know very little about programming, so I could really use some help.
I'm using Unity3D 2018.2.9f1
The app is for the Samsung's Gear VR

Timer
For any stuff using timers or wait I find Coroutines most of the time the best options.
You could either get the audio clip length and than wait for it
public AudioClip clip;
private void Start()
{
StartCoroutine(Wait(clip.length));
}
private IEnumerator Wait(float seconds)
{
yield return new WaitForSeconds(seconds);
// start fadeout here
}
or you could wait until it finishes playing
public AudioSource source;
// or wherever you start the music adioclip
private void Start()
{
source.Play ();
yield return new WaitUntil(()=> !source.isPlaying);
// start fadeout here
}
Fading
Here it depends a lot ... do you really switch Scenes by using LoadScene etc or do you just want to enable/disable certain content within one Scene?
And do you have 3D objects with materials and renderers or only 2D content using Unity.UI components?
The simplest solution for sure would be to place one overlay Canvas with the desired color as Image and simply fade it in and out. This is actually already available in the AssetStore and basically does
Uses an Overlay Canvas on top of everything with a certain color and animates it's alpha value (again using a Coroutine)
Makes sure that canvas is DontDestroyOnLoad so it isn't removed when we switch scenes
FadeIn the Canvas/Image => Fades out the current Scene
Load the other scene
FadeOut the Canvas/Image => Fades in the new Scene
Here is the source code (just cleaned it up a little)
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Fader : MonoBehaviour
{
private string _fadeScene;
private float _alpha;
private CanvasGroup _myCanvas;
private Image _bg;
private float _lastTime;
private bool _startedLoading;
private float _fadeInDuration;
//Set callback
private void OnEnable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
//Remove callback
private void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
public void InitiateFader(CanvasGroup canvasGroup, Image image, string scene, Color fadeColor, float fadeInDuration, float fadeOutDuration)
{
DontDestroyOnLoad(gameObject);
_fadeInDuration = fadeInDuration;
_fadeScene = scene;
//Getting the visual elements
_myCanvas = canvasGroup;
_bg = image;
_bg.color = fadeColor;
//Checking and starting the coroutine
_myCanvas.alpha = 0.0f;
StartCoroutine(FadeIt(FadeDirection.Out, fadeOutDuration));
}
private enum FadeDirection
{
In,
Out
}
private IEnumerator FadeIt(FadeDirection fadeDirection, float fadeDuration)
{
var timePassed = 0.0f;
switch (fadeDirection)
{
case FadeDirection.Out:
do
{
_alpha = Mathf.Lerp(0, 1, timePassed / fadeDuration);
_myCanvas.alpha = _alpha;
timePassed += Time.deltaTime;
yield return null;
} while (timePassed < fadeDuration);
_alpha = 1;
SceneManager.LoadSceneAsync(_fadeScene);
break;
case FadeDirection.In:
do
{
_alpha = Mathf.Lerp(1, 0, timePassed / fadeDuration);
_myCanvas.alpha = _alpha;
timePassed += Time.deltaTime;
yield return null;
} while (timePassed < fadeDuration);
_alpha = 0;
Initiate.DoneFading();
Debug.Log("Your scene has been loaded , and fading in has just ended");
Destroy(gameObject);
break;
}
}
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
{
//We can now fade in
StartCoroutine(FadeIt(FadeDirection.In, _fadeInDuration));
}
}
and
public static class Initiate
{
private static bool areWeFading;
//Create Fader object and assing the fade scripts and assign all the variables
public static void Fade(string scene, Color col, float fadeOutDuration, float fadeInDuration)
{
if (areWeFading)
{
Debug.Log("Already Fading");
return;
}
var init = new GameObject("Fader", typeof(Canvas), typeof(CanvasGroup), typeof(Image), typeof(Fader));
init.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
var fader = init.GetComponent<Fader>();
areWeFading = true;
fader.InitiateFader(init.GetComponent<CanvasGroup>(), init.GetComponent<Image>(), scene, col, fadeOutDuration, fadeInDuration);
}
public static void DoneFading()
{
areWeFading = false;
}
}
than You call this in a dedicated component like in order to be able to do it e.g. in a button's onClick
public class DemoScript : MonoBehaviour
{
//name of the scene you want to load
public string TargetSceneName;
public Color LoadToColor = Color.black;
public float FadeInDuration = 1.0f;
public float FadeOutDuration = 1.0f;
public void GoFade()
{
Initiate.Fade(TargetSceneName, LoadToColor, FadeOutDuration, FadeInDuration);
}
}
or since it is static simply use
Initiate.Fade(TargetSceneName, LoadToColor, FadeOutDuration, FadeInDuration);
from anywhere.
Instead of the LoadSceneAsync you could also do your enabling and disabling stuff if you prefer to do it in only one scene.
However in VR it is actually a bad idea to fade to completely black and let the user see nothing. It might lead to disorientation and cybersickness ...

Related

How to Jump by Button UI using Character Controller in Unity3D

I am calling JUMP function from a UI Button but unable to jump using Character Collider provided by Unity. Can someone please help me where am i going wrong?
PlayerMovement Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerControllerCC : MonoBehaviour
{
public FixedJoystick moveJoystick;
CharacterController _charController;
private Vector3 v_movement;
private Animator _animator;
public float moveSpeed = 0.1f;
public float gravity = 0.5f;
public float jumpForce = 0.5F;
private float originalstepOffset;
private float InputX;
private float InputZ;
// Start is called before the first frame update
void Start()
{
moveSpeed = 0.1f;
gravity = 0.5f;
jumpForce = 0.5F;
_charController = GetComponent<CharacterController>();
originalstepOffset = _charController.stepOffset;
_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
InputX = moveJoystick.Horizontal;
InputZ = moveJoystick.Vertical;
isWalking();
}
private void FixedUpdate()
{
playerMovement();
}
void playerMovement()
{
//Check Gravity
if (_charController.isGrounded)
{
_charController.stepOffset = originalstepOffset;
v_movement.y = -0.5f;
}
else
{
_charController.stepOffset = 0;
v_movement.y -= gravity * Time.deltaTime;
}
//player movement
v_movement = new Vector3(InputX * moveSpeed, v_movement.y, InputZ * moveSpeed);
float magnitute = Mathf.Clamp01(v_movement.magnitude);
v_movement.Normalize();
_charController.Move(v_movement * magnitute);
Vector3 lookDir = new Vector3(v_movement.x, 0, v_movement.z);
//Set rotation facing after player movement
if ((lookDir.x != 0) && (lookDir.z != 0))
{
transform.rotation = Quaternion.LookRotation(lookDir);
}
}
void isWalking()
{
if (InputX == 0 && InputZ == 0)
{
_animator.SetBool("isWalking", false);
}
else
{
_animator.SetBool("isWalking", true);
}
}
public void Attack()
{
_animator.SetTrigger("isAttacking");
}
public void Jump()
{
if (_charController.isGrounded)
{
v_movement.y = jumpForce * Time.deltaTime;
}
}
}
When button is clicked in UI it called the JUMP function. I am not using keyboard but FixedJoyStick hence using button to jump.
My Game looks like this and the UI. The up arrow key is the jump button.
The Game button Up Arrow Jump
Calling Jump Function in Button
Your problem lays on the OnClick() function of the button, it is interacting with the script but the script itself is not attached to any character in this case. What you did works when the script works by itself no matter where is attached (e.g. when you call all the objects with a tag).
What you need to do is to link the object which has the script to the OnClick() in the editor, then select from the dropdown menu the script component and then call the function you want.
Like This.
Image link since I'm new
Notice how what is linked are the Game Objects and then the script is selected.

Unity 2D player movement

I had my unity movement working on my computer, however when i try to play on my android it is not moving for me at all. I am sure it is probably a small error i am overlooking but i would be very appreciative of any help! I do not get any errors when i try yo run my code if that is of any assistance! I will supply the code below:
using UnityEngine;
using System.Collections;
//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;
public class PlayerControler : MonoBehaviour {
public Text countText; //Store a reference to the UI Text component which will display the number of pickups collected.
//public Text winText; //Store a reference to the UI Text component which will display the 'You win' message.
private double count; //Integer to store the number of pickups collected so far.
//Player movement controls
private Vector3 touchPosition; //where your finger touches screen
private Vector3 direction; //direction you drag sprite
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
public float speed = 10f; //Floating point variable to store the player's movement speed.
// Use this for initialization
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
//Initialize count to zero.
count = 0;
//Initialze winText to a blank string since we haven't won yet at beginning.
//winText.text = " "; //error here??
//Call our SetCountText function which will update the text with the current value for count.
//SetCountText ();
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
touchPosition.z = 0;
direction = (touchPosition - transform.position);
rb2d.velocity = new Vector2(direction.x , direction.y) * speed;
if(touch.phase == TouchPhase.Ended)
{
rb2d.velocity = Vector2.zero;
}
}
}
//OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
void OnTriggerEnter2D(Collider2D other)
{
//Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
if (other.gameObject.CompareTag ("PickUp"))
{
//... then set the other object we just collided with to inactive.
other.gameObject.SetActive(false);
//Add one to the current value of our count variable.
count = count + 1;
//Update the currently displayed count by calling the SetCountText function.
//SetCountText ();
}
}
Here is my 2D Player Movement Controller.
Code(Character Controller) -
using UnityEngine;
using UnityEngine.Events;
public class CharacterController2D : MonoBehaviour
{
[SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps.
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100%
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
[SerializeField] private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
[SerializeField] private Transform m_CeilingCheck; // A position marking where to check for ceilings
[SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded.
const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private Vector3 m_Velocity = Vector3.zero;
[Header("Events")]
[Space]
public UnityEvent OnLandEvent;
[System.Serializable]
public class BoolEvent : UnityEvent<bool> { }
public BoolEvent OnCrouchEvent;
private bool m_wasCrouching = false;
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
if (OnLandEvent == null)
OnLandEvent = new UnityEvent();
if (OnCrouchEvent == null)
OnCrouchEvent = new BoolEvent();
}
private void FixedUpdate()
{
bool wasGrounded = m_Grounded;
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
m_Grounded = true;
if (!wasGrounded)
OnLandEvent.Invoke();
}
}
}
public void Move(float move, bool crouch, bool jump)
{
// If crouching, check to see if the character can stand up
if (!crouch)
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// If crouching
if (crouch)
{
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// Reduce the speed by the crouchSpeed multiplier
move *= m_CrouchSpeed;
// Disable one of the colliders when crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = false;
}
else
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
if (m_wasCrouching)
{
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
// Move the character by finding the target velocity
Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
// And then smoothing it out and applying it to the character
m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (m_Grounded && jump)
{
// Add a vertical force to the player.
m_Grounded = false;
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
And here is the actual Character Movement Code -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
private void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if(Input.GetButtonDown("Jump"))
{
jump = true;
}
}
private void FixedUpdate()
{
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
jump = false;
}
}
Maybe the movement on android device is too small to be noticed. Try multiplying speed to delta time and then tweak the speed value to reach your desired movement speed.
rb2d.velocity = new Vector2(direction.x , direction.y) * speed * Time.deltaTime;
Make sure the script is attached to the game object with Rigidbody2D component. Also if your computer doesn't support touch, you can use mouse input to have the same result on computer and mobile device.
if (Input.GetMouseButtonUp(0))
{
rb2d.velocity = Vector2.zero;
}
else if (Input.GetMouseButton(0))
{
touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
touchPosition.z = 0;
direction = (touchPosition - transform.position);
rb2d.velocity = new Vector2(direction.x, direction.y) * speed * Time.deltaTime;
}
This code is also works on mobile devices.
Try adding Time.deltaTime or increasing the force with Time.deltaTime.

How to make button image change with on click anywhere on screen?

I am very new to Unity and I have trouble understanding on click possibilities with my UI buttons etc.. In my project, I have a button which changes its image whenever I click on it and the way I made it is: I created this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class OnClickScript : MonoBehaviour
{
public static int spritenumber=1;
public Button mybutton;
public Sprite square;
public Sprite circle;
public Sprite triangle;
public int counter = 1;
void Start()
{
mybutton = GetComponent<Button>();
}
public void changeButton()
{
if (PAUSESCRIPTE.isPaused == false)
{
counter++;
if (counter == 1)
{
mybutton.image.overrideSprite = square;
spritenumber = 1;
soundmanagerscript.PlaySound("buttonpress");
}
if (counter == 2)
{
mybutton.image.overrideSprite = circle;
spritenumber = 2;
soundmanagerscript.PlaySound("buttonpress");
}
if (counter == 3)
{
mybutton.image.overrideSprite = triangle;
spritenumber = 3;
counter = counter - 3;
soundmanagerscript.PlaySound("buttonpress");
}
}
}
}
I attached this script to my button, selected sprites which I want to use and I added on On Click() function to the button.
Afterwards I decided that I no longer want to change the sprite of my button by clicking on the button itself but rather by clicking anywhere on the screen. I tried using Input.GetMouseButtonDown(0) but got no results since I used it incorrectly. Any help on, how to achieve what I want, is very welcome. Thanks in advance.
Here's how I'd do it:
using UnityEngine.UI;
using UnityEngine;
public class ButtonScript : MonoBehaviour
{
// Public objects
public Sprite[] sprites;
//Private objects/variables
private Image buttonImage;
private int spriteIndex;
void Start()
{
buttonImage = GetComponent<Image>(); // Get the image component of your button
spriteIndex = 0; // Set the index to 0
buttonImage.sprite = sprites[spriteIndex]; // Set the image to the first image in your sprite array
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
spriteIndex++; // Increment the index
if (spriteIndex > sprites.Length - 1) // Ensure that you stay within the array size
{
spriteIndex = 0;
}
buttonImage.sprite = sprites[spriteIndex]; // Set the image
}
}
}
However, you need to change the image settings to:
Image Type: simple
Use Sprite Mesh: true
(maybe) Preserve aspect: true
As an answer to your comment above, I will suggest you to have a button in the background and your pause button above. Then, replace your Update() method with an event OnClick() as you did before.
Your pause button will catch the left click and your background button will not.
Be sure to tick Interactable in the Button component.
Then you can safly remove the Image component of your background button, if you don't need it.
What it means is you can create (or modify) a class for your pause button
using UnityEngine.EventSystems;
public class PauseButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public bool IsMouseOver = false;
public void OnPointerEnter(PointerEventData eventData)
{
IsMouseOver = true;
}
public void OnPointerExit(PointerEventData eventData)
{
IsMouseOver = false;
}
// --
// Your OnClick method
// --
}
Note: the using eventSystems.
Now you can use this bool value within a code like amengelbrecht send you.
I'll will copy and paste his code from his answer, and add the bool value based on the previous class above.
public class BackgroundButtonScript : MonoBehaviour
{
// Public objects
public Sprite[] sprites;
public PauseButton pauseButton;
//Private variables
private Image buttonImage;
private int spriteIndex;
private void Start()
{
buttonImage = GetComponent<Image>(); // Get the image component of your button
spriteIndex = 0; // Set the index to 0
buttonImage.sprite = sprites[spriteIndex]; // Set the image to the first image in your sprite array
}
private void Update()
{
if (Input.GetMouseButtonDown(0) && !pauseButton.IsMouseOver)
{
spriteIndex++; // Increment the index
if (spriteIndex > sprites.Length - 1) // Ensure that you stay within the array size
{
spriteIndex = 0;
}
buttonImage.sprite = sprites[spriteIndex]; // Set the image
}
}
}
This will allow you to click anywhere on your screen except if the mouse is over your pause button. In this case, OnClick from the pause button will be called.
Be careful
If your game is is pause and the user left click anywhere but the pause button, depends on how your pause works, the Update() method of BackgroundButtonScript will be called and can lead to if (Input.GetMouseButtonDown(0) && !pauseButton.IsMouseOver).

How to make the camera follow the character without dragging the background along with it in screen space camera render mode in Unity?

I am making a 2D platfomer and I am using screen space-camera render mode in canvas. Now the background fits inside the screen in every aspect ratio perfectly. But when I make the camera follow the character, the background also comes with it, making the character look like it is not moving.
Code for player movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
[SerializeField]
private float movementSpeed;
// Use this for initialization
void Start ()
{
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate ()
{
float horizontal = Input.GetAxis ("Horizontal");
HandleMovement(horizontal);
}
private void HandleMovement(float horizontal)
{
myRigidbody.velocity = new Vector2 (horizontal * movementSpeed, myRigidbody.velocity.y);
}
}
Here is the camera follow code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
Vector3 velocity = Vector3.zero;
public float smoothTime = 0.15f;
public bool YMaxEnabled = false;
public float YMaxValue = 0;
public bool YMinEnabled = false;
public float YMinValue = 0;
public bool XMaxEnabled = false;
public float XMaxValue = 0;
public bool XMinEnabled = false;
public float XMinValue = 0;
void FixedUpdate()
{
Vector3 targetPos = target.position;
//vertical
if (YMinEnabled && YMaxEnabled)
{
targetPos.y = Mathf.Clamp (target.position.y, YMinValue, YMaxValue);
}
else if (YMinEnabled)
{
targetPos.y = Mathf.Clamp (target.position.y, YMinValue, target.position.y);
}
else if (YMaxEnabled)
{
targetPos.y = Mathf.Clamp (target.position.y, target.position.y, YMaxValue);
}
//horizontal
if (XMinEnabled && XMaxEnabled)
{
targetPos.x = Mathf.Clamp (target.position.x, XMinValue, XMaxValue);
}
else if (YMinEnabled)
{
targetPos.x = Mathf.Clamp (target.position.x, XMinValue, target.position.x);
}
else if (YMaxEnabled)
{
targetPos.x = Mathf.Clamp (target.position.x, target.position.x, XMaxValue);
}
targetPos.z = transform.position.z;
transform.position = Vector3.SmoothDamp (transform.position, targetPos, ref velocity, smoothTime);
}
}
If you use screen space camera, then the Canvas will move with the camera. I would suggest using Sprite Renderer instead of Canvas panel for level background. If you need to scale the Sprite according to screen, do it from the code. Also, for scrolling the background, you can follow this tutorial:
https://unity3d.com/learn/tutorials/topics/2d-game-creation/2d-scrolling-backgrounds

Preserving object after a reload scene

In a scene of my quiz game I have an animation object that changes for another animation when a button to move to the next question is pressed (the button reload the scene). I would like to keep the animation, the last animation referenced to the object, after the scene is reloaded, but I don't know how. The object always returns to its normal state (the first animation).
I currently have a script called 'tower' referenced to the object where I make a static object and a DontDestroyOnLoad function:
public static SpriteRenderer towerAnimation;
void Awake()
{
DontDestroyOnLoad(gameObject);
towerAnimation = GetComponent<SpriteRenderer>();
}
And this code in the Update of 'GameManager' script:
public static int counterQuestionChances = 2;
void DestroyTower()
{
if (counterQuestionChances == 1)
{
Tower.towerAnimation.SetTrigger("error 1");
}
else
{
if (counterQuestionChances == 0)
{
Tower.towerAnimation.SetTrigger("error 2");
}
}
But it doesn't work. I'm taking shots in the dark because I don't know how to solve this. I'd appreciate if you could give me any ideas that can help me with this. Thanks!
You're going to have to use the SceneManagement library that Unity has so when the scene changes the method below called OnActiveSceneChanged gets called.
using UnityEngine.SceneManagement;
public class Tower : MonoBehaviour
{
public static SpriteRenderer towerAnimation;
public int storedCounter = 0;
void Awake()
{
DontDestroyOnLoad(gameObject);
towerAnimation = GetComponent<SpriteRenderer>();
SceneManager.activeSceneChanged += OnActiveSceneChanged;
}
private void OnActiveSceneChanged(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.Scene currentScene)
{
//tower animation stuff here
}
}