Working with arrays/list with C# components in Grasshopper 3D

≡放荡痞女 提交于 2019-12-13 04:52:54

问题


New user of Grasshopper 3D here, and I am in need of some C# syntax help for coding in Grasshopper 3D. I have a script, for example, that's pasted below:

public static int arraySum(int[] myArray){
    int someValue = 0;
    for(int i = 0; i < myArray.Length; i++){
       someValue += myArray[i];
    }
    return someValue;
}

The above static method sums all values of an array.

From my understanding of the scripting components of C# in Grasshopper, you cannot create static methods, as everything is a non-returning void method. You assign a variable (the output) as a psuedo-return, is that correct?

Knowing that - how do I implement my above script, for example, to a C# component?

Instead of having a "return", I simply assigned a variable, for example, A as the sum. But I ran into some issues there, for example, with some C# methods like .Length not working.

The format of a method in the C# component of Grasshopper 3D is the following:

private void RunScript(int x, ref object A){
}

回答1:


This is a pretty old question, but I will go ahead and complete it for completion's sake. In any GH Scripting component there are two zones to write code. In the image you see the private method RunScript and the other area in // <Custom Additional Code>

So I could write your code within the RunScript method like this:

 private void RunScript(List<int> myArray, ref object A)
 {

    int someValue = 0;
    for(int i = 0; i < myArray.Count; i++){
      someValue += myArray[i];
    }

    A = someValue;

 }

Notice that I redefined myArray as a list of type int like on the script component input:

Since it is a list, I use myArray.Count in the loop. Finally I use A = someValue to get the result in the output of the component.

I could also write the method in the // <Custom additional code> area as such:

  private void RunScript(List<int> myArray, ref object A)
  {

    A = arraySum(myArray.ToArray());

  }

  // <Custom additional code> 

  public static int arraySum(int[] myArray){
    int someValue = 0;
    for(int i = 0; i < myArray.Length; i++){
      someValue += myArray[i];
    }
    return someValue;
  }

  // </Custom additional code>

Which looks like this:

I change the incomming myArray.ToArray() since it comes in as a list to the component. In this second manner, your original code is pretty much the same.

Hope this helps answer an old question!



来源:https://stackoverflow.com/questions/19958584/working-with-arrays-list-with-c-sharp-components-in-grasshopper-3d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!