Loading a scene - unity3d

I have a "Start Game" button
public static bool GameIsStart;
public void changeCamera ()
{
if (GameIsStart == true)
return;
GameIsStart = true;
SceneManager.LoadScene ("Game");
}
}
``
There is a script that I added to the Prefabs
public GameObject [] gameobject;
private bool gameobject_IS_Spawn;
private float RandomPositionforX;
private int RandomObjects;
private void Update ()
{
if (StartGame.GameIsStart &&! gameobject_IS_Spawn)
{
StartCoroutine (Spawngameobject ());
gameobject_IS_Spawn = true;
}
}
IEnumerator Spawngameobject ()
{
while (true)
{
if (StartGame.GameIsStart)
{
yield return new WaitForSeconds (1.3f);
RandomPositionforX = Random.Range (-2.28f, 2.28f);
RandomObjects = Random.Range (0, gameobject.Length);
Instantiate (gameobject [RandomObjects], new Vector2 (RandomPositionforX, 24f), Quaternion.identity);
}
}
}
}
There is a button on the "Game" scene to access the preview
public void ChangeScene ()
{
SceneManager.LoadScene ("preview");
}
}
I click on the button, the "Preview" scene is loaded, but the "Start game" button does not work.
If I put in the "Preview" button SceneManager.LoadScene ("Game")
then I restart the scene ("Game") and everything works.
But if SceneManager.LoadScene ("Preview") but the buttons don't work.
When switching between scenes, is it necessary to stop Coroutine
How can this problem be corrected?

Without seeing the code it's a bit harder to find where the problem is coming from.
The only thing that is coming to my mind is that it may be something related with how the scene is stored and loaded after.
According to the Scene Manager Documentation, you could save the scene1 in a variable and keep the DontDestroyOnLoad(scene1) on its awake method, then add something like:
Scene scene2 = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene1); To the button that reloads the previous scene.

Related

Gun should shoot only when button is touched instead of entire screen

I've made a 3d game and I have a first person controller, control by a joystick. I want my player to shoot only when I touch a button on the screen, but now my player shoots if I touch anything on the screen. This is the script for the shoot function:
using UnityEngine;
using UnityEngine.UI;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public Button button;
// Start is called before the first frame update
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
button.onClick.AddListener(TaskOnClick);
}
// Update is called once per frame
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
}
void Shoot()
{
RaycastHit hit;
if( Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
}
}
void OnCollisionEnter(Collision collision)
{
Debug.DrawRay(collision.contacts[0].point, collision.contacts[0].normal, Color.green, 2, false);
}
void TaskOnClick()
{
Shoot();
}
}
Your Shoot() method runs whenever you press the "Fire1" button, since the only check you are doing is if (Input.GetButtonDown("Fire1")).
If you want to depend on a button to fire you need to take this part of the code out and call Shoot() whenever you click the button.
You can add the event to the button using code, as explained here
public Button m_YourFirstButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
or you could call it from the inspector by referencing your Gun monobehaviour.

Can't find GameObject in new scene in DontDestroyOnLoad

I have a GameController in Scene1 and I made it DontDestroyOnLoad.
When I loaded Scene2, I'm trying to find a GameObject in Scene2 and the thing is obj2 is null but obj1 is not.
Why?
How could I find the GameObjectInScene2?
public class GameController: MonoBehaviour
{
private void Awake()
{
DontDestroyOnLoad(this);
}
private void Start()
{
SceneManager.LoadScene("Scene2");
GameObject obj1 = GameObject.Find("GameObjectInScene1");
GameObject obj2 = GameObject.Find("GameObjectInScene2");
}
}
Start is not called again since your component already ran it in Scene1
You can register to SceneManager.sceneLoaded and do the find in the callback instead.
I would also store the references global like
private GameObject obj1;
private GameObject obj2;
void Start()
{
// This first line just makes sure the listener isn't added twice
SceneManager.sceneLoaded -= OnSceneLoaded;
// Whenever a scene is loaded call OnSceneLoaded
SceneManager.sceneLoaded += OnSceneLoaded;
obj1 = GameObject.Find("GameObjectInScene1");
SceneManager.LoadScene("Scene2");
}
void OnDestroy ()
{
// Always clean up listeners when not needed anymore!
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if(scene.name == "Scene2")
{
obj2 = Find("GameObjectInScene2");
}
}

Reload GameScene without reloading UIScene in Unity3d

I have 2 scenes "GamePlay" and "GameUI".
I load GameUI additively with GamePlay
void Awake () {
if (!instance) {
instance = this;
} else {
Destroy(this.gameObject) ;
}
SceneManager.LoadScene ("GameUI", LoadSceneMode.Additive);
DontDestroyOnLoad(this.gameObject);
}
Now when I reload the "GamePlay" scene using
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
How can I prevent reloading "GameUI" scene?
You could add an MonoBehaviour that is attached to the GameUI which contains a static bool that indicates if the object exists. Make your whole UI Scene a child of one object with the following script.
public class UIExistance : MonoBehaviour
{
public static bool Exists { get; private set; }
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
UIExistance.Exists = true;
}
void OnDestroy()
{
UIExistance.Exists = false;
}
}
When you are in your posted Awake method you can check with if(!UIExistance.Exists) whether the UI is already in the scene.

How to simulate a mouse up event?

There is a bug in my code: When I release the mouse out of the screen, the unity can't detect "GetMouseButtonUp", and when I move the released mouse back to the screen, it detects the "GetMouseButton" which should not.
So when the mouse out of the screen, I want simulate send a mouse up event to let the unity detect "GetMouseButtonUp".
How to simulate a mouse event?
Pseudo code
bool mouseIsDown = false;
public void Update()
{
Rect screenRect = new Rect(-Screen.width/2, -Screen.height/2, Screen.width, Screen.height);
If(screenRect.Contains(Input.mousePosition))
{
if(mouseIsDown && !Input.GetMouseButton(0))
OnMouseUp();
if(Input.GetMouseButton(0))
{
OnMouse();
if(!mouseIsDown)
{
OnMouseDown();
mouseIsDown = true;
}
}
}
}
public void OnMouseDown()
{
// Do something
}
public void OnMouse()
{
// Do something
}
public void OnMouseUp()
{
// Do something
}
I am not sure if I correctly understand your question. But, you can use these functions the same way you would use the Start() Update() Awake() etc. functions
void OnMouseUp () {
}
void OnMouseDown (){
}

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
}
}