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

时间:2018-10-30 16:22:19

标签: c# list grasshopper rhino3d

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

1 个答案:

答案 0 :(得分:1)

如果我正确地阅读了您的代码,则问题是allAgents列表会越来越长。如您所料,那是因为您只在顶部创建了一次列表,然后只在显示for的{​​{1}}循环中添加了该列表。

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