- Home /
My object is not reappearing
When running the game I achieve to set inactive my gameobject however it never respawns (set active), do I have my code wrong?
using System;
using UnityEngine;
public class FlammableThings : MonoBehaviour
{
public int health; //Vida del objeto
public GameObject cenizas; //Particulas de cenizas
[Range(0f, 10f)]
public float burnTime; //Tiempo hasta que se quema
public Camera mainCam; //Camara actual
public float maxCameraDistance; //Distancia para reaparecer
bool isNotPresent;
// Update is called once per frame
void Update()
{
if (health <= 0 && !isNotPresent)
{
Instantiate(cenizas, transform.position, Quaternion.identity);
//Destroy(gameObject, 3f);
Invoke("Burn", burnTime);
}
Respawn();
}
//Desactiva el objeto
void Burn()
{
gameObject.SetActive(false);
isNotPresent = true;
Debug.Log("Object burnt");
}
//Reaparece el objeto
void Respawn()
{
if (Math.Abs(gameObject.transform.position.x - mainCam.transform.position.x) >= maxCameraDistance)
{
if (isNotPresent)
{
gameObject.SetActive(true);
isNotPresent = false;
Debug.Log("Object respawned");
}
}
}
}
Answer by RodrigoSeVeN · Sep 01, 2020 at 04:46 PM
Two problems.
First, the Update method will not run on an inactive Game Object.
Second, to reactivate an inactive Game Object you need a reference to it, in case you try to do this externally, or it will not be found for being inactive.
I suggest you do this without turning it off at all.
You can do something like using a boolean to replace the active/inactive state, making sure your update method only runs the respawn method.
private bool _isActive = true;
void Update ()
{
if (_isActive)
{
/// Logic here.
}
Respawn();
}
Also, replace these:
gameObject.SetActive(false);
gameObject.SetActive(true);
isActive = false;
isActive = true;
Thank you so much Rodrigo, definetely I'll try your answer; also you are the first person that answers me so thank you again
Let me know if you got this sorted out. Cheers.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Multiplayer Game Player Camera not Working 2 Answers
Pan RTS camera controller without changing elevation/zoom 0 Answers
Keep hud between cameras 0 Answers