- Home /
Problems with Invoke
I'm still pretty new to Unity, but if there's an answer to this, I haven't seen it yet.
I'm trying to use Invoke to give a slight delay to re-instatiate my player object after it dies, but no matter how I try I cannot get the Invoke method to actually execute.
Here's the code:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public static int lives;
public LifeCounter lifeCounter;
private LevelManager levelManager;
// Use this for initialization
void Start(){
lives = 2;
MakePlayer();
}
void MakePlayer() {
Instantiate(Resources.Load("Player"));
}
public void OneUp(){
lives++;
}
public void PlayerDie(){
Destroy(GameObject.Find("Player(Clone)"));
lives -= 1;
lifeCounter = GameObject.Find("LifeCount").GetComponent<LifeCounter>();
lifeCounter.LoseLife();
Debug.Log(lives);
if (lives >= 0){
Invoke("MakePlayer", 2);
}else {
//Game Over
levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>();
Cursor.visible = true;
levelManager.LoadLevel(SceneManager.sceneCountInBuildSettings - 1);
}
}
}
If I use a regular call to re-instantiate the player, it works fine, and if I use and Invoke for the initial call it works fine too, but I can't figure out how to make it do what I actually want.
Thanks in advance for any answers you can give me.
Try Send$$anonymous$$essage ins$$anonymous$$d if it's already on the same object? $$anonymous$$aybe?
Send$$anonymous$$essage does call the method, but doesn't appear to provide any sort of delay.
Are you getting any error in console ? put Debug.Log("Some$$anonymous$$essage")
and test the call sequences or by putting breakpoints.
There aren't any errors. If I put Debug messages before and after the Invoke, they both get called. And I put one inside the $$anonymous$$akePlayer() which show that it just isn't getting called the second time around.
Answer by madscientist1234 · Jul 31, 2020 at 03:42 AM
try to move the void MakePlayer under the invoke idk. it looks correct except from the number 2 in the Invoke thread. try 2f; instead of 2;