How to move to next scene using scene manager in Unity 5? - c#

I am doing a tutorial that is using unity 4 and they are using this:
Applicaiton.LoadLevel(Appliaction.loadedLevel +1);
in order to move on to the next scene. I am using unity 5, and it is telling me to use scene manager since the previous method is now obsolete.
What is the new code to replace the one above?

The Scene struct has a buildIndex variable to store the index. Therefore, to load the next scene:
using UnityEngine.SceneManagement;
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
if(currentSceneIndex<SceneManager.sceneCount-1)
{
SceneManager.LoadScene(currentSceneIndex + 1);
}

using UnityEngine;
using UnityEngine.SceneManagement ;
public class next_level : MonoBehaviour
{
public void next_levl(){
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1 ) ;
}
}

Related

Trying to add a delay to an gameobject spawner [duplicate]

This question already has answers here:
How to make the script wait/sleep in a simple way in unity
(7 answers)
Closed 4 months ago.
I'm a new C# programmer here in the early stages of creating a project in Unity where you play as a microbe that needs to eat blue food pellets to grow and survive. I've got the blue food pellets to spawn randomly across the map but I want to add a delay because too much is spawning at once. This is what I've attempted to do so far. Any help would be appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
public class Spawner : MonoBehaviour
{
public GameObject food;
public async void Wait(float duration)
{
Vector3 randomSpawnPosition = new Vector3(Random.Range(-50, 50), 1, Random.Range(-50, 50));
Instantiate(food, randomSpawnPosition, Quaternion.identity);
await Task.Delay((int)duration * 1000);
}
// Update is called once per frame
void Update()
{
async void Wait(float duration);
}
}
What I've tried:
Putting the delay function in the update function. The program just gets confused and thinks I'm trying to call the function.
Calling the function after combining all my code into the one function, the program rejects this.
Like the default code snippet says, Update runs every frame. Using Task.Delay to delay events would still spawn objects with the same frequency, they would only start spawning delayed.
The typical way to do this in Unity is to use a coroutine.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
[SerializeField] GameObject food;
protected void OnEnable()
{
StartCoroutine(SpawnFoodRoutine());
}
IEnumerator SpawnFoodRoutine()
{
while(enabled)
{
SpawnFood();
var waitTime = Random.Range(1f, 5f);
yield return new WaitForSeconds(waitTime);
}
}
void SpawnFood()
{
Vector3 randomSpawnPosition = new Vector3(
Random.Range(-50f, 50f),
1f,
Random.Range(-50f, 50f));
Instantiate(food, randomSpawnPosition, Quaternion.identity);
}
}
I have made this prefab called “pellet”, then I have created a new gameObject called “SpawnManager” and, finally, added this script to SpawnManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnPellet : MonoBehaviour
{
public GameObject prefab;
public bool canSpawnNewPellet = true;
public float delay;
void Update(){
if(canSpawnNewPellet){
Invoke("SpawnNewPellet", delay);
canSpawnNewPellet = false;
}
}
void SpawnNewPellet()
{
GameObject instance = Instantiate(prefab);
instance.transform.position = new Vector3(Random.Range(0,10), Random.Range(0,10), 0);
canSpawnNewPellet = true;
}
}
The I have dragged and dropped/edited values on the fields in the inspector (Prefab, canSpawnNewPellet and Delay). Those are public fields inside the script, so you can populate them drag and dropping directly from your assets folder.
Hit play and you have a new spawn every X seconds where X is the value of delay in seconds.
Screenshot of the game executing after 21 seconds.
What does it do?
Every frame it evaluates if can spawn a new pellet (bool canSpawnNewPellet). If it can, then it starts an invocation of another method with X seconds (and mark the bool as false since we don’t want to call more invocations during de instantiation of our first sample).
For more references: https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
Edited: typo.

How to save and add a value obtained in the game?

I'm making a store for my game and I'm making a system where the score I get in the game is saved and every time you play it adds and saves too, but this last part isn't working I don't know why, I'm taking a variable from another script called score it receives the value I got and had to add it to the previous value but it doesn't happen.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CoinsManager : MonoBehaviour
{
public GameObject YellowSquare;
private int totalScore;
void Start()
{
YellowSquare.GetComponent<Text>().text = GameController.score.ToString();
totalScore = PlayerPrefs.GetInt("lastScore", GameController.score);
}
void Update()
{
SaveMoney();
}
void SaveMoney()
{
totalScore = GameController.score++;
PlayerPrefs.SetInt("lastScore", totalScore);
}
}
Why is the GameController.score completely detached from this? I would expect you rather do
// actually load the previous score into GameController.score
GameController.score = PlayerPrefs.GetInt("lastScore", GameController.score);
// then AFTER this update the text
YellowSquare.GetComponent<Text>().text = GameController.score.ToString();
.. and then in Update rather do
// Btw do you really want your score to be a counter of how many FRAMES you have played? o.O
GameController.score++;
PlayerPrefs.SetInt("lastScore", GameController.score);
// also update the text after changing the value
YellowSquare.GetComponent<Text>().text = GameController.score.ToString();

Start() being called 2 times with Photon

I'm making a multiplayer system. I have a strange situation about Start(). When the first player joins there is 2 logs "player joined". So, when second player joins, their model instantiates twice (there is PhotonNetwork.Instantiate in Start()). I guess Start() is being called 2 times somehow?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;
public class MPRoomServer : MonoBehaviour
{
public GameObject rocket;
public TMP_Text title;
// Start is called before the first frame update
void Start()
{
PhotonNetwork.Instantiate(rocket.name, new Vector3(20.4928417f,4.3900001f,-10.116004f), Quaternion.identity);
title.text = "Room " + PhotonNetwork.CurrentRoom.Name;
Debug.Log("New player joined");
}
// Update is called once per frame
void Update()
{
}
}
OnJoinedRoom() works even when you create a room. So, my scene was loaded 2 times, and the script was used 2 times.

How to display Debug.Log messages on Text.UI after restarting the same scene? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I'm working on a simple little game in Unity where the objective is to use a floating hand to guide the ball into the basket and every time the ball enters the basket, the game resets due to an hidden collider with a trigger inside the basket.
The feature I'm trying to implement:
Every time the ball goes into the basket the text.UI updates to reflect your new score, beginning with 0 points and the score increments by 1 for every slam dunk.
The issue:
How do I convert the "Debug.Log" into a text.UI?
I was only successful in updating the score on the Unity console and I wasn't able to convert these events to the text.UI.
The text.UI GameObject I've created only displays the text "New Game" and never gets updated.
Update: I've created a new script to solve this and I got this error:
NullReferenceException: Object reference not set to an instance of an object
ChangingText.Start () (at Assets/Scripts/ChangingText.cs:12)
The process:
1. Creating a GameObject and script to keep data after scene restarts.
I've created a script to keep the score after restarting the the same scene, I have only one scene.
I've attached this script to the game object: "GameController" and that's how was able to keep the score updated.
The name of the scene is:
"DunkingPractice"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameControl : MonoBehaviour
{
// Giving it a name called "Control", any other script can interact with it
public static GameControl Control;
public int score;
// Called before Start()
private void Awake()
{
// If there's a control already, delete this
// If there's no control, make this the control object
if (Control == null)
{
Control = this;
DontDestroyOnLoad(gameObject); // Don't destory the object when a scene is loaded
}
else if (Control != this)
{
Destroy(gameObject);
}
}
}
Image that I've included to demonstrate this:
Creating "GameController" GameObject and Script
2. Creating an hidden trigger collider GameObject inside the basket with a scenemanager.loadscene inside the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class RestartTrigger : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Ball")
{
SceneManager.LoadScene(0);
}
}
}
Image that I've included to demonstrate this:
Creating a trigger collider and restart trigger
3. Creating a script to Keep score and adding this component to the aforementioned trigger collider
Notice that the script refers to the Game Control script I've created earlier.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeepingScore : MonoBehaviour
{
static void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Ball")
{
GameControl.Control.score++;
if (GameControl.Control.score == 1)
{
Debug.Log("You have " + GameControl.Control.score + " point");
}
else if (GameControl.Control.score != 1)
{
Debug.Log("You have " + GameControl.Control.score + " points");
}
}
}
}
Here's another image that I've included:
Creating a script to keep score and attaching it to the trigger field
4. Creating a Text.UI on screen and creating a new script to change text only for an error to appear
This is the script that produces the NullReferenceException error:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangingText : MonoBehaviour
{
public Text scoreText;
void Start()
{
scoreText.text = GameControl.Control.score.ToString();
}
}
Here's another image to demonstrate:
Creating a text object
Here's a screen recording I've made to show how my scene currently looks like:
https://www.screencast.com/t/JUBsUkHuHgHC
Do you have any suggestions?
Thank you
NullReferenceException is happened if one of your instance is null and you are trying to modify it, in the log error, it show that :
Object reference not set to an instance of an object ChangingText.Start ()
It means that your scoreText instance does not connect to any UI and it's null. To resolve that, just simply create text UI gameObject and drag it into the 'scoreText' field in the object that is assigned with ChangingText script

Saving Data to Variable With Different Script File Unity C#

Iam confused saving data to variable with different script file.
For Example :
File player.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class player : MonoBehaviour {
public int coin = 1000;
}
File levelupstorage1raw.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Linq;
public class levelUpStorage1Raw : MonoBehaviour {
public player Player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnClickWood () {
Player.coin = Player.coin + 1000;
}
}
In this script player.cs :
public class player : MonoBehaviour {
public int coin = 1000;
}
I have inisial the coin = 1000, this mean int coin have 1000.
In Other script file levelupstorage1raw.cs :
public player Player;
// Use this for initialization
public void OnClickWood () {
Player.coin = Player.coin + 1000;
}
I have add more coin 1000 to Player.coin.
Now my question is : where the Player.coin 1000 is save ? is it save to it own file variable Player.coin or
is it save to player.cs file variable coin ?
If it save to player.cs file variable coin then variable coin now should have 2000.
You clearly have to learn a bit more about programming. Try looking for tutorials online.
Regarding your question, if I simplify things a bit to give you an idea:
A variable is something that can change. What is written in your Player.cs file is the default value, the one it will have when starting the program. When you write Player.coin = Player.coin + 1000;, the variable value changes, so Player.coin is now 2000.
At this point the first value (1000) is lost because the variable in your program has been set to 2000. But this has nothing to do with the file.
When you run your program, your file has already been transformed to a program. The file with the code is just there to tell the computer how to create the program, but it won't be modified when you run the program.
I hope this helps you understand what happens in your example. I still thing you should look for tutorials. Even basic stuff will be really difficult to achieve if you don't know the basics

Categories

Resources