- Home /
OnTriggerEnter Bad Performance - Bad Code?
I have the following script set up to deploy AI cars from a pool of 13. Each trigger has an array of spawn points, which are just empty objects.
Currently I only have one trigger set up and when the player triggers it, there is a very noticeable pause. Is my code that horrific?
As I said, the array of cars is only 13. I don't get why there is this pause because before I was drawing from a pool of 13 inactive cars, I had it hardcoded with over 100 cars in the scene and it was working flawlessly... not sure how this "optimising" managed to lower performance.
I'm not the greatest coder by any means (I'm quite crap, actually), so any insight into what I have done incorrectly would be amazeballs ;)
#pragma strict
var SpawnerArray : GameObject[]; // Assign Spawners in inspector
var AICarArray : GameObject[]; // Assign cars in inspector
var iRandom : int = 0;
var iRandom2 : int = 0;
var iIndex : int = 0;
function OnTriggerEnter(Other : Collider)
{
if (Other.tag == "Player")
{
iRandom = Random.Range(0, SpawnerArray.Length);
for (var i = 0; i < iRandom; ++i)
{
iRandom2 = Random.Range(0, AICarArray.Length);
iIndex = iRandom2;
if (!AICarArray[iIndex].active)
{
AICarArray[iIndex].transform.position = SpawnerArray[i].transform.position;
AICarArray[iIndex].transform.rotation = SpawnerArray[i].transform.rotation;
AICarArray[iIndex].SetActive(true);
}
}
}
}
This isn't your issue but if you are tweaking, why do this
iRandom2 = Random.Range(0, AICarArray.Length);
iIndex = iRandom2;
ins$$anonymous$$d of
iIndex = Random.Range(...);
since you aren't using iRandom2 anywhere. The time is probably in the SetActive() since that has to run Awake and Start for all the AICarArray[] gameobjects that get selected
Yeah, I was using iIndex as I was reseting it to cycle through if the car was already active. I just forgot to change it back.
I didn't think of it having to run start/awake etc for each car. I'll try setting the cars to active from the beginning and just modify their positions etc. Though before I had 100 or so inactive cars and I was using OnTriggerEnter to set them to active...
Hmm, no it's not that. I disabled the scripts on the cars... still the same issue. It does seem to make a difference as to how many cars are being spawned but I don't see why it should, as it is never more than four.
There's a subtle difference between ++i and i++ but what it is I don't remember; I usually see that in the form of i++ doubt it makes a difference.
Answer by arklay_corp · Apr 23, 2014 at 08:13 AM
It doesn't look wrong, I'd check if the problem is in another script attached to your cars
Yeah it's odd. It's fine on device too, just doing it in the editor, so I'm not too worried.