[SOLVED] Methods driven by scene being run

Hi,

My name is David and I am new to the forums, so please excuse my etiquette if it is poor. I have a specific question relating to my personal “flavor” of NumberWizard. I have created 3 separate ranges for the user to select. 1-100, 1-1000, and 1-10,000. Now, when I created it in console only, I simply created separate start methods for which range the user wanted and they set all my int (min, max, guess) ranges.

But now, I am finding a problem when I try to transfer that same logic to separate
scenes. I created 3 separate scenes, based on which range is clicked by the user. I would like to create a function that is activated based on which scene is selected so that I can set my int (max, min, guess) for the different range in whichever scene the user selected. These one of the attempts I tried…

So I am probably way off with Application.loadedLevelName, but hopefully this shows what I am trying to do. My 3 scenes are onehundred,onethousand, and tenthousands.

Now, I’m sure there is a more efficient way to change my range in the same scene, and maybe we can use that as a solution, but I am curious if there is a way to let the script make “if” decisions based on the name of the scene currently running.

I tried hard to search for the verbage I would use to let the script recognize the scene and allow “if” type functions, but I’m fresh to coding and the resources are overwhelming. I may have looked it straight on and not realized it. My current solution is separate scripts for each scene, which my efficient minded brain can’t stand.

Also, I want to use correct terms, so please correct my use of function and method if I am off and give me as many definitions or terms for what I am trying to say. I would really like to get a better handle on them. Thank you so much for any help that you can give.

1 Like

Bump

1 Like

Ouch! :slight_smile:

I started to reply to your topic earlier today, but it was going to get a little lengthy, so I had to stop.

I believe you have three main queries which I will try to answer below;

  • Application.loadedLevelName - this is actually obsolete in the more recent versions of Unity, but in version 4.x.x you will still be able to use it. It returns a string. One improvement you could make to your existing Restart method would be to use a local variable to store the returned value from Application.loadedLevelName, and not call it three times, as it won’t have changed, then merely compare the string, perhaps something like this;

    public void Restart()
    {
        string levelName = Application.loadedLevelName.ToUpper();
    
        switch (levelName)
        {
            case "ONEHUNDRED":
                StartGame100();
                break;
            
            case "ONETHOUSAND":
                StartGame1000();
                break;
            
            case "TENTHOUSAND":
                StartGame10000();
                break;
        }
    }
    

The switch statement works fairly much like a series of if statements, you could of course use if and else if, as at least one of those conditions much be true to start the game.

Note, I have used the ToUpper method so that my comparison of strings is more accurate, this will prevent against issues if you were to rename a scene using mixed-case, e.g. “OneThousand”.

I also corrected the StartGame method call in the third if statement in your example as it was calling the StartGame100 method.

  • The “efficient brain” - you are spot on. The solution you have works, and that’s good, especially for perhaps putting together a prototype. What you could consider now is a series of refactoring exercises to reduce any duplication in your project. You have already identified you are using three scripts and three scenes, and as the only significant difference is the min/max values, it wouldn’t be very difficult to rework your project so that you use just the one NumberWizard script to run the game, and just use a different range based on the input from the player.

  • Correct terminology - I would suggest that in many cases, function and method are used fairly interchangeably, without any real concern of the subtle differences between the two. The following is an extract from a web page discussiing Object Oriented Programming, I have linked it below for your reference.

    Once you have created objects, you want them to be able to do something. This is where methods come in. A method in object-oriented programming is a procedure associated with a class. A method defines the behavior of the objects that are created from the class. Another way to say this is that a method is an action that an object is able to perform. The association between method and class is called binding. Consider the example of an object of the type ‘person,’ created using the person class. Methods associated with this class could consist of things like walking and driving. Methods are sometimes confused with functions, but they are distinct.

    A function is a combination of instructions that are combined to achieve some result. A function typically requires some input (called arguments) and returns some results. For example, consider the example of driving a car. To determine the mileage, you need to perform a calculation using the distance driven and the amount of fuel used. You could write a function to do this calculation. The arguments going into the function would be distance and fuel consumption, and the result would be mileage. Anytime you want to determine the mileage, you simply call the function to perform the calculation.

    How does this differ from a method? A function is independent and not associated with a class. You can use this function anywhere in your code, and you don’t need to have an object to use it.

    Now, what if you were to associate the function with an object of the type ‘car?’ For example, you want to be able display the mileage of the car on the dashboard. In this case, the mileage calculation has become a method because it is a procedure associated with the car’s class. Every time you create a new object of the type ‘car’ using the car class, this method will be part of the object. The action the car is now able to perform is to calculate mileage. It is the same calculation as performed by the stand-alone function but is now bound to the car.

I hope the above is of use.

Note, you don’t need to paste screenshots of your code into the forum, you can just paste your code in directly and format it. Screenshots are very useful however when it comes to displaying issues/errors/details from the Unity editor, such as the Inspector or Hierarchy.

If you would like to work through a refactor of your code so that it only uses the one NumberWizard script for the main game rules then let me know, happy to offer some help if I can.


See also;

Ok, sorry for the delay. Had a busy day yesterday. First off, let me just say thank you for responding and taking the time to help. I really appreciate it. I had to delete my entire project and start over as it was bugging out and putting the name of methods instead of the name of the script in my component add. It was weird. Anyway, built it all over again with only one number wizard script and the wierdness is gone! So, I have created a script with a string variable. That variable is determined by my loaded level name. And the specific name allows me to run methods, using switch case function, to update my integer values based on my loaded level name. here is my script…


using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class NumberWizard : MonoBehaviour {
	int max;
	int min;
	int guess;
	int maxGuess;	
	
	public Text guessText;
	public Text test;

	void Start () {
		Restart();
	}
	
	public void Restart(){
		string levelname = Application.loadedLevelName.ToUpper();
			
			switch (levelname){
				
				case "game100":
					StartGame100();
					break;
				case "game1000":
					StartGame1000();
					break;
		}
	}
	
	void StartGame100(){
		min = 1;
		max = 100;
		guess = 50;
		guessText.text = guess.ToString();
		max = max + 1;
		maxGuess = 4;
	}
	
	void StartGame1000(){
		min = 1;
		max = 1000;
		guess = 500;
		guessText.text = guess.ToString();
		max = max + 1;
		maxGuess = 7;
	}
	
	public void GuessHigher(){
		min = guess;
		NextGuess();
	}
	
	public void GuessLower(){
		max = guess;
		NextGuess();
	}
	
	void NextGuess(){
		guess = (min + max) / 2;
		guessText.text = guess.ToString();
		maxGuess = maxGuess - 1;
			if (maxGuess <= 0){
				Application.LoadLevel("win");				
		}		
	}
}

You will notice I renamed my levels with “game 100”, etc. However, it doesn’t work… I put “guess” into my ui text object as a place holder and it does not update to the int value created by the StartGame100 method. The text does update when I select higher or lower, so the UI text object is being updated by the number wizard script, however, I don’t believe the StartGame100 method is running, as it isn’t changing any values at scene load.

Here you can see the number wizard object selected and the Guess Text assigned to the Object guess. So, what am I doing wrong?


	public void Restart(){
		string levelname = Application.loadedLevelName.ToUpper();
			
			if(levelname = "game100"){
				StartGame100();
		}
		
	}

Here is another one I tried, but I am doing it wrong… something about cant convert string to bool?

1 Like

Hi,

When you do a comparison you need to use ==, a single = is used for setting a value.

In your switch statement you are checking for a lowercase value, but on the line above you have uppercase’d the level name, these won’t match, you need to be consistent and either uppercase the values in your switch statement or use ToLower() when you retrieve the level name.

Rob, you are the man! I am going to just leave this post and start a new one if I decide to do one game scene. Thank you so much!!!

1 Like

You’re very welcome, if you do decide to, feel free to tag me (@Rob ) and I will be happy to help/guide if you run into any problems.

Also, if you do, please do share you experiences and end result with the community, it is always beneficial for others to be encouraged and inspired :slight_smile:

One quick question, what command would I use in the current unity to turn the level loaded into a string variable to drive functions, since loadedLevelName doesn’t work in current versions?

1 Like

Hi,

If you are referring to Unity 5+ / 2017+ then you would use SceneManager.

Example;

using UnityEngine;
using UnityEngine.SceneManagement;

public class Example : MonoBehaviour
{
    private void Start()
    {
        string sceneName;

        sceneName = SceneManager.GetActiveScene.name;

        Debug.Log("This scene is called, " + sceneName);
    }
}

Hope this helps :slight_smile:


See also;

Privacy & Terms