- Home /
Problem is not reproducible or outdated
How to start a function from another scene.
Hello, I've searched for the answer of this question but I could not find it. The question is really simple, I have in one scene this script:
function OnGUI(){
if(GUI.Button(Rect(267,0,77,33),"Next Wave")){
Application.LoadLevel("Asteroid");
}
}
And in another scene this one:
var IsSpawning : boolean = false;
var Asteroid : Transform;
var WaveNumber = 1;
static var Score : int = 0;
static var Lives : int = 3;
static var HighScore : int = 0;
static var EnemyCounter = 0;
function Start(){
WaveFunction(WaveNumber);
}
function Update(){
if(Lives <= 0){
if(Score > HighScore){
HighScore = Score;
}
Application.LoadLevel("ScreenLoss");
}
if(EnemyCounter == 0 && !IsSpawning){
Application.LoadLevel("ScreenShop");
}
}
function UpdateWave(){
WaveNumber++;
WaveFunction(WaveNumber);
}
function WaveFunction(Wave : int){
var EnemysInThisRound = Wave * 4;
IsSpawning = true;
for(var i = 0 ; i < EnemysInThisRound; i++){
var position = Vector3(Random.Range(-6, 6), 12, 0);
Instantiate(Asteroid, position, Quaternion.identity);
yield WaitForSeconds(Random.Range(1, 1.5));
EnemyCounter++;
}
IsSpawning = false;
}
My question is how do I start the UpdateWave function when I press the NextWave Button in the first scene? Thank you -Nelis
Answer by aaronov · May 09, 2013 at 10:44 AM
You can't call functions from scripts from different scenes because only one scene can be loaded at one time. You can however have a GameObject that persists between scenes by adding the following:
function Awake () {
DontDestroyOnLoad (transform.gameObject);
}
With the above code in place you should be able to place the function below in your second script and whenever the level is loaded it will call the UpdateWave() function.
function OnLevelWasLoaded (level : int) {
UpdateWave();
}
You may want to add some code in there to check the level index and only call UpdateWave() on certain levels, such as "Asteroid".
Yes, you would add that to the second script in your original question.
I did that. But when I'm in my AsteroidScreen and I press play and kill all the enemys, I go to the ShopScreen. If I press the 'NextWave' button there, the asteroids just spawn in the shop screen. If it could help, here is my project folder: http://www.mediafire.com/download.php?xm543lps0t2rmns
It's purely up to you how it should all work I merely gave an example of what I thought you wanted to achieve. In saying that - I think you need to do what I mentioned at the end of my answer and only call UpdateWave() when level index == index of asteroid scene.
I have added the index check. Also thank you for helping me.