- Home /
Checking to see if a loaded level is equal to a member of an integer array
I am currently creating a mouse lock/hide script and have an object in each scene with a script. The script checks a list of if statements to find which level is being used by using Application.loadedLevel. Currently with this setup I will need TONS of if statements. So I was wondering if I could create a whitelist/blacklist sort of setup to check an array of integers and find if any integers in that array was the currently loaded level. Could this be done? Any help would be great since I feel that all those if statements will drop performance by a lot. Thanks!
in a for loop check if whitelist[i] == Application.loadedLevel.
$$anonymous$$y code is this: using UnityEngine; using System.Collections;
public class cursorLockedFalse : $$anonymous$$onoBehaviour {
public int [] whitelist;
public int [] blacklist;
void Awake () {
for(int i=0; i<100; i++)
{
if(whitelist[i] == Application.loadedLevel)
{
Cursor.visible = false;
Screen.lockCursor = true;
}
else if(blacklist[i] == Application.loadedLevel)
{
Cursor.visible = true;
Screen.lockCursor = false;
}
}
}
}
It's still not working correctly. It doesn't lock the cursor or make the cursor invisible on the whitelist. Any help would be appreciated.
This code will iterate through both the Lists.
If loaded level matches to level of either List. It will do the assigned work.
foreach( int level in whitelist)
{
if( level == Application.loadedlevel)
{
Cursor.visible = false;
Screen.lockCursor = true;
}
}
foreach( int level in blacklist)
{
if( level == Application.loadedlevel)
{
Cursor.visible = false;
Screen.lockCursor = true;
}
}
Answer by crohr · Jun 10, 2015 at 11:30 PM
Your code causes an IndexOutOfBounds exception if either list is below 100 in length. Also, I assume that you want this to check every time your game loads a new level.
If you attach the following script to an empty gameObject in the first scene that is loaded, you should be golden. (You may notice that at first the cursor doesn't actually disappear, just click in the game window to focus it and the cursor go away.)
using UnityEngine;
using System.Collections;
public class cursorLockedFalse : MonoBehaviour {
public int [] whitelist;
public int [] blacklist;
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
private void OnLevelWasLoaded (int level)
{
for(int i=0; i<whitelist.Length; i++)
{
if(whitelist[i] == Application.loadedLevel)
{
Cursor.visible = false;
Screen.lockCursor = true;
}
}
for(int i=0; i<blacklist.Length; i++)
{
if(blacklist[i] == Application.loadedLevel)
{
Cursor.visible = true;
Screen.lockCursor = false;
}
}
}
}
Your answer
Follow this Question
Related Questions
Error with an Array 1 Answer
How to convert String array to int array 1 Answer
Number parse 1 Answer
Check if an int is equal to an array int 3 Answers
How do I create a save scene feature though int value in c# 2 Answers