Home > other >  Unity - Prefab won't activate after being made unactive
Unity - Prefab won't activate after being made unactive

Time:10-18

I am simply trying to cut a tree down and respawn it. I am doing this simply by using timers to make the tree prefab inactive and then active.

The tree will become inactive after 1 second (1st wait timer) and then active after 2 (second wait timer).

Strangely however, the second wait timer doesn't seem to work as shown in the logs below. Any help would be great.

This is my ChopTree script:

public class ChopTree : MonoBehaviour
{
    private bool touching;

    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("Touching tree");
        touching = true;
        Debug.Log(touching);
    }

    private void OnTriggerExit(Collider other)
    {
        Debug.Log("Not Touching tree");
        touching = false;
        Debug.Log(touching);
    }

    private void Update()
    {
        if (Keyboard.current.enterKey.wasPressedThisFrame)
        {
            if (touching == true)
            {
                StartCoroutine(TreeSpawner.DeleteAndRespawn());
            }
        }
    }
}

And this is the tree spawner script:

public class TreeSpawner : MonoBehaviour
{

    // Assign tree prefab.
    [SerializeField]
    private GameObject tree;

    // Access-point for tree script.
    private static TreeSpawner instance;

    // Spawn the tree when the game Starts.
    void Start()
    {
        instance = this;
    }

    IEnumerator Respawn(float timeToDespawn, float timeToRespawn)
    {
        yield return new WaitForSeconds(timeToDespawn);
        Debug.Log("Deleting...");
        tree.SetActive(false);
        Debug.Log("Deleted...");
        Debug.Log("Respawning...");
        yield return new WaitForSeconds(timeToRespawn);
        Debug.Log("Respawn Timer done...");
        tree.SetActive(true);
        Debug.Log("Respawned...");
    }

    public static IEnumerator DeleteAndRespawn()
    {
        Debug.Log("Deleting and respawning tree");
        yield return instance.StartCoroutine(instance.Respawn(1f, 2f));
    }
}

Here are the order of the logs:

enter image description here

As you can see the log to say the respawn timer is done never happens. Why is that?

CodePudding user response:

I guess you have set the "tree" field to a GameObject where you have placed the TreeSpawner script. When the "tree" GameObject is inactivated...

tree.SetActive(false);

...the TreeSpawner scripts is then also stopped.

A coroutines also stops when the GameObject it is attached to is disabled with SetActive(false)

  • Related