1

我在 List 中累积 Point3ds 时遇到问题。当我更改 int 代理的数量(通过蚱蜢中的 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 ;
        }
4

1 回答 1

1

如果我正确阅读了您的代码,那么您的问题是allAgents列表越来越长。正如您所猜测的那样,这是因为您在顶部创建了一次列表,然后您只在for循环中添加了// Initialize Agents.

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

于 2018-10-30T17:03:45.610 回答