Foreach error with [ExecuteInEditMode]

I am currently making a system where i can easily asign points where my AI pathfinding will move between, like a route… This is for the editor so i can make the AI work better… BUT i am currently having a problem with [ExecuteInEditMode]…

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Route : MonoBehaviour
    public bool EditMode;
    public Vector3[] routes;
    public List<GameObject> routes_obj = new List<GameObject>();
    void Update()
        if (Application.isPlaying && !EditMode)
                foreach (Transform obj in transform)
                        if( != "Cube")
                        if (obj.tag == "RN")
                                if (Application.isPlaying)
            routes_obj = new List<GameObject>();

This is just a part of the code as pasting it all in would take alot of space… my problem is that the foreach loop only returns every second object (i have 7 objects… “#0” → “#5” and “Cube”…) All the numbered once have the “RN” tag… but only #1, #3, #5 get’s deleted… What am i doing wrong? i amde the exact same piece of code (modified slightly but nothing that changes the actual code) without the “[ExecuteInEditMode]” and it works totally fine,… Is it an error with Unity? should i do this another way? i really don’t know what’s going on…

I hope this is enough information…

My guess is that Unity’s foreach-in-transform is not properly whining that you’re destroying objects as you’re iterating through it. You should never add or remove elements from an array you’re foreaching through. Now, “foreach-in-transform” isn’t an array, but it seems that Unity is using the object to determine which object is next, and destroying one is disrupting that order.

Generally you’d use a shallow copy of the array for foreach to modify, but in this case it seems more straightforward to build a list of transforms to destroy later (I don’t recall how to get a list of children out of a transform)

Something like this:

Transform[] things = new Transform[transform.childCount];
int nextElement = 0;

foreach(Transform obj in transform) {
  if ( "RN" ) things[nextElement++] = obj;

foreach(Transform obj in things) {
  if ( null != obj ) Destroy(obj);