Hello! I have problem with this code here,when i start the game in the editor, it starts to spam add the transform in the list until the fps drops dead. It should only add one object once or until the object gets active again when i change ships at runtime. I need it at update so it updates the current active transform Only 1 ship is active at start, then i swap between ships with a button, and when i do so, the current active ship becomes inactive while the next ship in the list gets active and so on. The script is a world boundary script for space ships. Code (csharp): public List<Transform> boundObjects = new List<Transform>(); void LateUpdate () //Call in LateUpdate so it happens after physics calls { foreach (ShipMovement t in FindObjectsOfType<ShipMovement>()) boundObjects.Add(t.transform); foreach(Transform t in boundObjects)
In what way? Thats the part of the script that adds the transform, the rest of the script is codes for prevent the object to leave the world and the size of it. I guess you mean this? i posted that by mistake. Code (csharp): foreach(Transform t in boundObjects)
I'm not sure I understand what you're trying to do. Obviously your code will add to boundObjects every frame, even if there's just one active at a time you aren't doing any checking for if that object is already in the list so every new frame you will have another instance of it added.
I have a "change ship" script so i can swap between different ships by check and uncheck in inspector. The code i posted is a part of a world boundary script that adds 1 current active ship to that list, but as you said it adds the same ship each frame and i dont want that because it drains the fps like crazy. So what i want is the script to add 1 ship at time and once to the list as it gets activated in inspector, and then remove it from the list and add the new one that just got activated. Maybe a max object limit in the list will do it?
If I understand you correctly you just want to clear the list before you add. Code (CSharp): // Clear list. boundObjects.Clear(); foreach (ShipMovement t in FindObjectsOfType<ShipMovement>()) { boundObjects.Add(t.transform); }
Wont this keep filling the list each frame with the same object or keep clear it when it is on Update?
No, the list will be emptied and only the objects found in the current update will be added. It should work fine.
Ah ok, i thought it would keep clear and add the same object, but for what i can see it works as you said. Thanks for your help!
I'm sorry, but just curious here.. You want your active ship to be in a specific list for bound transforms (something like that?). If I understood that correctly, I would suggest that you add/remove your active ship to the list when you click the button that changes/cycles your ship. That would be much more sensible and not require Update/LateUpdate to re-write the list constantly, even if nothing has changed.