'Error for respawn enemy and player script unity 4 version
I have a problem with this script that gives me errors. My project consists of respawn the player and the prefab enemies after being destroyed after 5 seconds in the same original position but the script gives me a lot of errors and I don't know how to fix them. can you give me some help to correct the script? Thanks
using UnityEngine;
using System.Collections;
public class respawn : MonoBehaviour {
void OnCollisionEnter(Collision collision) {
StartCoroutine(Respawn(5f, 5f));
}
IENumerator Respawn(float timeToDespawn, float timeToRespawn) {
yield return new WaitForSeconds(timeToDespawn);
gameObject.SetActive(false);
yield return new WaitForSeconds(5f);
gameObject.SetActive(true);
}
Solution 1:[1]
You spelled IEnumerator wrong. The N needs to be lowercase. Consider using an IDE. That would have detected your mistake and would also give you huge lot of help developing. I suggest either Microsoft VisualStudio or Jetbrains Rider
Edit: Your object still won't respawn because when you disabled the object, the coroutine will be stopped since it's part of that gameobject. Instead you could use invoke. It continues when your gameobject gets disabled. Thisshould work:
using UnityEngine;
using System.Collections;
public class respawn : MonoBehaviour {
void OnCollisionEnter(Collision collision) {
Invoke(nameof(Despawn), 5f);
Invoke(nameof(Respawn), 10f);
}
void Despawn(){
gameObject.SetActive(false);
}
void Respawn(){
gameObject.SetActive(true);
}
}
As you can see Invoke simply delays the execution of a method.
Solution 2:[2]
script gives me many errors and doesn't work. How Can you fix it, please?
Assets/respawn.cs(7,12): error CS0103: The name nameof' does not exist in the current context Assets/respawn.cs(7,5): error CS1502: The best overloaded method match for UnityEngine.MonoBehaviour.Invoke(string, float)' has some invalid arguments
Assets/respawn.cs(7,5): error CS1503: Argument #1' cannot convert object' expression to type string' Assets/respawn.cs(8,12): error CS0103: The name nameof' does not exist in the current context
Assets/respawn.cs(8,5): error CS1502: The best overloaded method match for UnityEngine.MonoBehaviour.Invoke(string, float)' has some invalid arguments Assets/respawn.cs(8,5): error CS1503: Argument #1' cannot convert object' expression to type string'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Bernardo |
