- Home /
For loop multiplying the action by the lenght of the array.. WHY ?!
So i have a script that puts in an array every GameObjects that enter the trigger, remove them when they exit it and aplly a force to all of them when they stay in the trigger. Here is the script :
import System.Collections.Generic;
static public var inUpObjects: List.<GameObject>;
function Start () {
inUpObjects = new List.<GameObject>();
}
function Update () {
}
function OnTriggerEnter(other:Collider) {
inUpObjects.Add(other.gameObject);
}
function OnTriggerStay() {
for (var inUpObject:GameObject in inUpObjects) {
inUpObject.rigidbody.AddForce(Vector3.down * Atmocube.gravity);
}
}
function OnTriggerExit(other:Collider) {
inUpObjects.Remove(other.gameObject);
}
Okay it's working fine but when a second GameObject enter the array the force is multiplied, when a third GameObject enter the array the force is again multiplied, etc..
Any ideas WHY ?!
Perhaps you need to do something to check to see if that object is already in the List.
What do you mean ? Why would i have to check ? The force is a gravity force so it needs to always be active..
EDIT : I've tried : function OnTriggerEnter(other:Collider) { for (var searchedObject:GameObject in inUpObjects) { if (searchedObject != other.gameObject) { inUpObjects.Add(other.gameObject); } } } But it still increasing the force..
Answer by jonSG · Apr 14, 2014 at 07:32 PM
OnTriggerStay() gets called gets called once per frame for every collider that is touching the trigger.
2 objects in the trigger, you get 2x the force and so on if you are also itterating over the collection.
In effect, you are duplicating what the OnTrigger system is doing for you.
What if you get rid or your OnTriggerEnter and OnTriggerExit then do something similar to:
function OnTriggerStay( Collider inUpObject ) {
inUpObject.rigidbody.AddForce(Vector3.down * Atmocube.gravity);
}
GOD THX ! I took like 5hours to make all of this and end up knowing that is just needed 1 line of code..
THHHHHX ! I'm so dumb..
Your answer
![](https://koobas.hobune.stream/wayback/20220613142715im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
[C#]For-loop in For-loop crashes Unity. 1 Answer
naming a variable with a number 1 Answer
going through each item of a multi-dimensional array 1 Answer
GUI button image next 2 Answers
ios cant access variables in array 1 Answer