I have a bus, the script on the bus says I have 3 riders on board.
The bus collides with a GameObject called BusDropOffPointCollider.
This triggers the OnCollisionEnter successfully.
I would like the riders to spawn some time apart instead of all at once.
For some reason they all spawn at once even though I have tried many variations of a delay.
Nothing in the code is static.
i do get all the debug message.
private void OnCollisionEnter(Collision collision)
{
// if bus collies with BusDropOffPoint then instatiate all the riders on the bus
if (collision.gameObject.name == "BusDropOffPointCollider")
{
// only spawn the riders once since collisions occur as bus passes over BusDropOffPointCollider
if ((!haveSpawnedRiders) && (numberOfRiders > 0))
{
Debug.Log("Collided: " + collision.gameObject.name);
// spawn the rider away from the bus on the curb
Vector3 _spawnPosition = this.transform.position + new Vector3(3.0f, 0.0f, -2.0f);
for (int i = 0; i < numberOfRiders; i++)
{
Debug.Log("Start:" + System.DateTime.Now);
//delay(10.0f);
Thread.Sleep(3000);
// spawn the bus rider
SpawnTheRider(_spawnPosition); // (this just instantiates a GameObject)
Debug.Log("End:" + System.DateTime.Now);
haveSpawnedRiders = true;
}
}
}
// set the number of riders on the bus to 0
this.numberOfRiders = 0;
}
I think you’d be better off using a coroutine rather than trying to use Thread.Sleep. I’m actually surprised it didn’t cause your whole app to suspend for 3 secs at a time.
Indeed - Thread.Sleep() shouldn’t be used.
A Coroutine would be great. You can send the # of passengers to drop off (and that would spawn), insert the delay in a loop to spawn them, and after the bus is empty, set the passengers to zero.
Small note: You never need to use the “this” keyword when you’re programming, unless you have ambiguity.
int a = 4, b = 2;
void TestMethod(int a) {
this.a = a; // means the field 'a' gets the value of 'a' from the function parameter here.
b = a * 4; // field b is automatic here
}
You are starting the Coroutine three times. That’s why they all appear at the same time.
I would suggest making an enum or pool that displays that your currently spawning something.
F.E before starting the Coroutine put an if-statement like if(notSpawning) only if this return true start the Coroutine and set notSpawning to false. Put the yield statement at the end and after the yield statement set the bool notspawning to true again.
Yes, as @MilKID said, you’re calling it 3 times. This would be a way to call it once
IEnumerator SpawnTheRider(Vector3 _spawnPosition, int spawnCount, float delay) {
for(int i = 0; i < spawnCount; ++i) {
Instantiate(Resources.Load("Characters\\Sporty_Granny\\Sporty_Granny"), _spawnPosition, Quaternion.identity); // really no need to make a variable here, since it wasn't used.
yield return new WaitForSeconds(delay);
}
}