Requesting help with Time.time & Instantiate script.

Greetings

So I want to instantiate an object after a certain time (4 seconds) and the code runs fine, no errors appear and I can execute the game but no object instantiates after the 4 seconds?
Here’s my code:

` using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

public GameObject EnemyFab;
float gameClock;

void Update () 
{
    gameClock = Time.time;
    
    if (gameClock == 4.0f)
    {
        Debug.Log("yo");
        Vector3 position = new Vector3(Random.Range(-5, 5), 11, 0);
        Instantiate(EnemyFab, position, Quaternion.identity);
    }
}

}
`

I know there is a couple of unnecessary things in there but I’ve been trying everything I could think of to make the Enemy Instantiate. By the way I am not getting any yo’s in the debug. I’d be grateful for any help or suggestions!

EDIT: Also I had another question; So instead of destroying my object after it collides with an enemy I set renderer.enabled = false; and then a couple of seconds later it reapers when I set renderer.enabled = true; but all that time is isn’t rendered its still physically has a collier and a transform and can still collide with objects. So I would prefer a ?Function?Code?Method?(don’t even know what to call it :expressionless: ) instead of renderer.enabled that will physically move it or disable it for a certain amount of time?

Thank you very much for your time :slight_smile:

The update code runs every frame. The time between frames varies depending on the performance of your code, graphics, PC speed, etc (what we call framerate is how many frames are run per second). So you don’t know exactly how long between frames.

The chances that an update will run in exactly 4.0 seconds is small. You’ll need to check it differently, you need to check if at least 4 seconds have passed.

Here’s the “Unity” way of doing it:

public GameObject EnemyFab;
float spawnTime = 4;
 
void Update () 
{
    if (spawnTime >= 0 && Time.time >= spawnTime)
    {
        Debug.Log("yo");
        Vector3 position = new Vector3(Random.Range(-5, 5), 11, 0);
        Instantiate(EnemyFab, position, Quaternion.identity);
        spawnTime = -1;
    }
}

public void SpawnInSeconds(float seconds) {
    spawnTime = Time.time + seconds;
}

So basically what we’re doing is keeping track of when the enemy should spawn, and putting it in spawnTime. It starts with 4, so initially the enemy will be spawned after 4 seconds. Then every frame we checked whether the time to spawn has already passed, and if it has we will spawn the enemy, and set the time to spawn to a negative number (meaning it will never spawn until we change it). If you want to spawn in X seconds, simply call SpawnInSeconds(X), and it will set spawnTime to be X seconds from now.

About your second question, you can deactivate it with:

enemy.gameObject.SetActive(false);

and then enable it again with

enemy.gameObject.SetActive(true);