将列表重置为新的对象数量

Resetting List to new quantity of objects

我在列表中累积 Point3ds 时遇到问题。当我更改 int 代理的数量(通过 grasshopper 中的 gui 滑块)时,数量会不断增加,而不是重置为新的数量。我猜我应该在某个地方重新初始化列表或每次更改值时都将其清除?这样做的正确做法是什么?

        protected override void SolveInstance(IGH_DataAccess DA)
        {
            BoundingBox box = new BoundingBox(0.0, 0.0, 0.0, boundx, boundy, boundz);
            DA.SetData("Bounding Box", box);
            DA.SetData("Start", "The current trigger is set to " + started.ToString());

            // Initialize Agents
            for (int i = 0; i < agents; i++)
            {
                double xPos = RandomfromDouble(0.0, boundx);
                double yPos = RandomfromDouble(0.0, boundy);
                double zPos = RandomfromDouble(0.0, boundz);

                Point3d pos = new Point3d(xPos, yPos, zPos);        // Create Agent Start Position
                Vector3d vec = new Vector3d(xPos + RandomfromDouble(-360.00, 360.00), yPos + RandomfromDouble(-360.00, 360.00), zPos + RandomfromDouble(-360.00, 360.00));  // Create Agent Start Vector

                Agent agent = new Agent(pos, vec, alignment, separation, cohesion, neighborRadius);
                allAgents.Add(agent);

                DA.SetData("Debug", "# of Agents Created: " + allAgents.Count);
            }

            // Get agent positions
            List<Point3d> agentPositions = new List<Point3d>();
            List<Vector3d> agentVectors = new List<Vector3d>();

            agentPositions = allAgents.Select(agent => agent.Pos).ToList();
            agentVectors = allAgents.Select(agent => agent.Vec).ToList();

            DA.SetData("Agent Count", allAgents.Count);
            DA.SetDataList("Agent Points", agentPositions);
            DA.SetDataList("Agent Vectors", agentVectors);

            if (started)
            {
                DA.SetData("Start", "The current trigger is set to " + started.ToString());

                for (int i = 0; i < generations; i++)
                {
                    DA.SetData("Debug", "# of Generations: " + i);

                    foreach (Agent agent in allAgents)
                    {
                        DA.SetData("Debug", "# of Agents: " + i);

                        agent.UpdateAgent(allAgents);
                    }
                }
            }
            else if (!started)
            {
                DA.SetData("Start", "The current trigger is set to " + started.ToString());
                //return;
            }
        }

        public double RandomfromDouble(double from, double to)
        {
            double diff = Math.Abs(from - to);
            return rnd.NextDouble() * diff + from ;
        }

如果我没看错您的代码,您的问题是 allAgents 列表越来越长。正如您猜到的那样,那是因为您在顶部创建了一次列表,然后您只在 for 循环中添加了它,即 // Initialize Agents.

如果此时您打算重置列表,那么在您进入 for 循环之前,我认为您需要执行 allAgents.Clear()。这将清空列表,然后循环遍历并在循环中添加新的 Agents。