Unity 2018 script to make panel scroll up wont work if I go to the game scene before the credits scene - c#

I am working on a game in Unity3D (what else would I be making) and so far I have the Main menu scene, the game scene and the Credits scene.
There is a script I made (shown below) That will make the panel holding the names scroll up that works fine if I select the credits scene from the main menu. But here is the problem. If I go to the game first and then go back to the main menu rand select credits nothing happens. Any ideas?
using UnityEngine;
using System.Collections;
public class ScrollCredits : MonoBehaviour
{
public GameObject Canvas;
public int speed = 1;
public string level;
private void Start()
{
Canvas.transform.Translate(Vector3.up * Time.deltaTime * speed);
StartCoroutine(waitFor());
}
private void Update()
{
}
IEnumerator waitFor()
{
yield return new WaitForSeconds (69);
Application.LoadLevel(level);
}
}

You moved your Translate inside the Start(), it won't work that way.
Only StartCoroutine should be in Start(), like this :
public GameObject canvas;
public float speed = 0.1f;
public string sceneName;
public float timer;
private void Start()
{
StartCoroutine(WaitFor());
}
private void Update()
{
canvas.transform.Translate(Vector3.right * Time.deltaTime * speed);
}
IEnumerator WaitFor()
{
yield return new WaitForSeconds (timer);
SceneManager.LoadScene(sceneName);
}
Note : I changed LoadLevel to SceneManager.LoadScene because it's deprecated, and will be removed in the future.

Related

Player movement doesn't work after reloading the scene in Unity

Using Unity 2021.3.16f1.
I followed this tutorial from Brackeys to make the pause menu for my flappybird like game, my player movement stops working after I exit the main game to the main menu and return to the game.
Part of player code responsible for movement:
public class birdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myRigidbody.velocity = Vector2.up * flapStrength;
FindObjectOfType<AudioManager>().Play("jump");
}
}
}
Part of pause menu code responsible for loading the main menu scene:
using UnityEngine.SceneManagement;
public class pauseMenu : MonoBehaviour
{
public static bool gameIsPaused = false;
public GameObject pauseMenuUI;
public void loadMenu()
{
Time.timeScale = 1f;
SceneManager.LoadScene("Title");
}
}
Part of code responsible for loading the main game scene:
using UnityEngine.SceneManagement;
public class playButton : MonoBehaviour
{
public void loadLevel()
{
SceneManager.LoadScene("Main game");
}
}
I tried changing the play button code that loads the main game, in the scene hierarchy my main menu scene is 0 and my main game scene is 1. The play button is on the main menu.
I turned this
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Into this
SceneManager.LoadScene("Main game");
But nothing happened, I tried searching on google but I have no idea how to search for the right answers.
Your problem has nothing to do with scene loading. That said your code for loading level is fine as it was:
using UnityEngine.SceneManagement;
public class playButton : MonoBehaviour
{
public void loadLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
Issue could be in your pauseMenu script but you only provided a part of the code. You need to make sure your Time.timeScale is set to 1f when the level scene is loaded.
I would suggest setting the default value for flapStrength. Also in void Start there is Time.timeScale set to 1f just to be sure. You could do this in the pauseMenu script.
public class birdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength = 10f;
void Start()
{
Time.timeScale = 1f;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myRigidbody.velocity = Vector2.up * flapStrength;
FindObjectOfType<AudioManager>().Play("jump");
}
}
}
I hope the answer helped. The issue is that the problem could be anywhere. It is necessary to go through all the values and examine the behavior of the player. Didn't an error appear that would stop the game? If the problem persists, you would need to edit the question and add more information.

disabling gameObjects after seconds using object pooling and coroutines

I'm developing a simple VR shooter in unity, i use object pooling for the bullets (Lasers here)
this is the ObjectPool script, here i istantiate a list of bullets in the start() method and disable them.
public class ObjectPool : MonoBehaviour
{
public static ObjectPool instance;
private List<GameObject> pooledObject = new List<GameObject>();
private int amountToPool = 20;
[SerializeField] private GameObject laserPrefab;
private void Awake()
{
if (instance == null)
{
instance = this;
}
}
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < amountToPool; i++)
{
GameObject obj = Instantiate(laserPrefab);
obj.SetActive(false);
pooledObject.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObject.Count; i++)
{
if (!pooledObject[i].activeInHierarchy)
{
return pooledObject[i];
}
}
return null;
}
}
This is the Script attached to the gun where i get the pooled bullet and set it to active
public class FireLaserGun : MonoBehaviour
{
public GameObject laserBeamModel;
public Transform laserSpawnPoint;
// Start is called before the first frame update
public void FireGun()
{
GameObject laser = ObjectPool.instance.GetPooledObject();
if (laser != null)
{
laser.transform.position = laserSpawnPoint.position;
laser.transform.rotation = laserSpawnPoint.rotation;
laser.SetActive(true);
Debug.Log("BOOM");
}
else
{
Debug.Log("Laser is null");
}
}
}
I'm trying to disable the bullet after two seconds was fired using a coroutine in the script that moves the bullets:
public class LaserBeamMove : MonoBehaviour
{
private Rigidbody rb;
public float thrust = 10.0f;
float waitTime = 2.0f;
private IEnumerator coroutine;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
coroutine = WaitToDisable(waitTime);
StartCoroutine(coroutine);
}
void FixedUpdate()
{
rb.velocity = transform.forward * thrust;
}
private IEnumerator WaitToDisable(float waitTime)
{
yield return new WaitForSeconds(waitTime);
gameObject.SetActive(false);
Debug.Log("bullet disabled after " + waitTime + "seconds");
}
}
Strangely first seconds of the game everything seems fine, all the bullets start as inactive and every bullet becomes active when fired and inactive after two seconds.
After some seconds bullets dont become inactive anymore (actually only some of them do).
this is a screenshot of the console log, when i fire i print "BOOM" and when a bullet becomes inactive i print "bullet disabled after 2 seconds"
As you can see this down't work for every bullet and i don't understand why.
Am i doing something wrong with the courutine?
https://i.stack.imgur.com/rMJgg.png
Take the code you have in void Start() and move it to a new void OnEnable. The reason is that Start is only called once, the first time the object holding the script is enabled (e.g when the scene loads, when you instantiate a bullet etc), OnEnable is called every time the object is enabled, which is what you want here. You could also use Awake but IMHO that's best kept separately for initialisation stuff only so you can keep the code tidy and separate out game logic from init logic.

FixedUpdate slightly fired up even if scene is paused with Time.timeScale = 0f

I'm a newbie in unity & c# . The FixedUpdate function does some Rigidbody action (here pushing the cube over the z axis)
However the scene works fine in development (cube starts at z = 0 )
The problem is in build , the cube starts at certain distance means z = 5 or 6
According to my understanding , I believe this is caused due to FixedUpdate being fired for some milli seconds before it notice Time.timeScale = 0f in PauseGame function
And when it notice this it behave as expected.
But then on Restart function when being called up (called by a button) using SceneManager.LoadScene function cube starts with z= 0 in build.
clip at development and clip with bug at build
where did I go wrong, thanks in advance.
image of bug at build, cube starts at certain position
image of development which working fine as expected cube starts at z = 0
public class GameController : MonoBehaviour
{
public GameObject tapToStart;
private void Start()
{
tapToStart.SetActive(true);
PauseGame();
}
private void Update()
{
StartGame();
}
public void Restart()
{
SceneManager.LoadScene("Game");
}
public void PauseGame()
{
Time.timeScale = 0f;
}
public void StartGame()
{
tapToStart.SetActive(false);
Time.timeScale = 1f;
}
}
public class PlayerScript : MonoBehaviour
{
public new Rigidbody rigidbody;
public float force;
private void Update(){}
private void FixedUpdate()
{
rigidbody.AddForce(0, 0, force * Time.deltaTime);
}
}
You are correct! FixedUpdate is called at relatively'fixed' intervals. It doesn't matter if something is done in your other code and you need it to get updated immediately. FixedUpdate will just keep pressing on at a a regular interval.
You can verify your suspicions by placing the line:
rigidbody.AddForce(0, 0, force * Time.deltaTime);
Inside your Update() function.
Now, onto the solution. I suggest that create place the following code in your currently empty Update() function:
if(Time.timeScale = 0f){
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
}
Now, as soon as you press the pause button, it will be detected on the next frame of Update() and the object will be frozen. This will likely occur even before FixedUpdate is called. Of course, if you want to 'restore' the velocity and angular velocity when you unpause, you will need to store that data, and then set it back up when you unpause the game.
The issue has been solved .. I can't pause on start,
need to create a Boolean in PlayerScript.
public class PlayerScript : MonoBehaviour
{
public new Rigidbody rigidbody;
public float force;
public bool isGameStart; // this Boolean
private void Update(){}
private void FixedUpdate()
{
if (isGameStart)
{
rigidbody.AddForce(0, 0, force * Time.deltaTime);
}
}
}
and using that bool value , we need to use rigidbody component.
and in StartGame function in GameController we must assign true to that bool value
public class GameController : MonoBehaviour
{
public GameObject tapToStart;
public PlayerScript playerScript;
private void Start()
{
tapToStart.SetActive(true);
PauseGame();
}
private void Update()
{
StartGame();
}
public void Restart()
{
SceneManager.LoadScene("Game");
}
public void PauseGame()
{
Time.timeScale = 0f;
}
public void StartGame()
{
tapToStart.SetActive(false);
Time.timeScale = 1f;
playerScript.isGameStart = true;
}
}
this worked for me , this solution was given by a Youtuber "Unity city".. credits to him.

Unity problem activating a function with parameters in camera from another script in GameObject Enemy

I have a script that makes the camera do a shake by putting a button because
It is a public access function, if I do it that way when placing a button it works well but what I cannot achieve is to call the function so that every time my player collides with an enemy he makes the shake. I hope you can help me.
The shake code in camera is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShaker : MonoBehaviour {
private float shakeAmount = 0.5f;
private float shakeTime = 0.0f;
private Vector3 initialPosition;
private bool isScreenShaking = false;
void Update () {
if(shakeTime > 0)
{
this.transform.position = Random.insideUnitSphere * shakeAmount + initialPosition;
shakeTime -= Time.deltaTime;
}
else if(isScreenShaking)
{
isScreenShaking = false;
shakeTime = 0.0f;
this.transform.position = initialPosition;
}
}
public void ScreenShakeForTime(float time)
{
initialPosition = this.transform.position;
shakeTime = time;
isScreenShaking = true;
}
}
The enemy code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControladorEnemigoCirculoMediano : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Here I don't know what to call the public void function ScreenShakeForTime (float time);
I already tried many things online but when my character comes into contact with the character, I don't do the shake in the camera.
}
}
}
You can create Unity-singleton in your ScreenShaker class like:
class ScreenShaker
{
public static ScreenShaker Instance {private set; get;};
void Awake() {
Instance = this;
}
}
And than from any place to call like:
ScreenShaker.Instance.ScreenShakeForTime(2f);
This is the easiest way, but maybe it's better to create standard singeleton(it's up to you).
And also don;t forget to destroy it on OnDestroy()
can you tell me in enemy game object collider isTrigger is enable or not
if it is not enable then use OnColliderEnter2D(Collision2D other){} for collision detection

After ending the scene need to start new scene

I'm doing an educational game for kids..
But I stopped at the end of the scene
I could not make a code to start the new scene..
in the First Script
when play game the scenes does not stop until the last scene.
YouWin.pictureInPlace++;
I searched a lot and did not find my question, so I consulted you. It was easier to do a button to go to the Next scene but I prefer to do it automaticly
I think this task can be accomplished by the boolean but its need to reference game object.. and the script on 2 images.
The First Script (Manager) has put on Four images At Canvas..
The second one (YouWin) I put on empty GameObject..
thanks for the help
The first script (Manger)
using UnityEngine;
using UnityEngine.EventSystems;
public class Manager : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
Vector2 pos1;
public GameObject pos2;
private bool canMove;
public GameObject winner;
void Start()
{
pos1 = transform.position;
canMove = true;
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log(eventData);
}
public void OnDrag(PointerEventData eventData)
{
if (canMove)
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, pos2.transform.position);
if (distance < 50)
{
transform.position = pos2.transform.position;
transform.localScale = pos2.transform.localScale;
canMove = false;
winner.GetComponent<YouWin>().pictureInPlace++;
}
else
{
transform.position = pos1;
}
}
}
The second script (YouWin)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YouWin : MonoBehaviour
{
public int NumberOfImages;
public int pictureInPlace;
public string sceneName;
void Update()
{
if (pictureInPlace == NumberOfImages)
{
StartCoroutine(LoadScene());
Debug.Log("You Win!");
}
}
IEnumerator LoadScene()
{
yield return new WaitForSeconds(1.5f);
SceneManager.LoadScene(sceneName);
}
}
It looks like you didn't reference YouWin in your Manager script. You should include it by adding it as a global variable public YouWin <variable_name>; or by referencing your empty GameObject and getting the YouWin component:
public GameObject emptyObject;
emptyObject.GetComponent<YouWin>().picturesInPlace++;
After all thanks for helping me but I was able to find the right solution
just make in the first Script (Manager) :
bool static Done;
void Start()
{
bool Done = false;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, pos2.transform.position);
if (distance < 50)
{
transform.position = pos2.transform.position;
transform.localScale = pos2.transform.localScale;
canMove = false;
bool Done = True;
}
}
and just call it from the second Script (YouWin)
public string sceneName;
void Update()
{
if(Youwin.Done)
{
StartCoroutine(LoadScene());
}
}
IEnumerator LoadScene()
{
yield return new WaitForSeconds(0.5f);
SceneManager.LoadScene(sceneName);
}
This IS The right solution ;

Categories

Resources