foreach(method() in methods)

Hey. I need help understanding how to loop over several methods in a list. Using the code below I get the error message “Method name expected” when trying to call force() in the foreach-loop (line 10). Why can’t I do this? And if it’s not possible, what’s an alternative? I need to have several different forces for different game objects and don’t want to re-write the forces method every time. I would just like to add a method to this list.

List<Vector3> forces = new List<Vector3>();

void Awake(){
        forces.Add(Gravity());
}

Vector3 Force(){
        Vector3 sumForces = Vector3.zero;
        foreach(Vector3 force in forces){
                sumForces += force();
        }
        return sumForces;
}

Vector3 Gravity(){
        return Vector3.zero;
}

force isn’t a method, it’s a local variable which contains an item from the forces list. Remove the () from there, you don’t need it.
Also it is a good idea to separate your naming to verbs and nouns. Give variable and classes noun names and verbs for functions, methods. Also avoid the similar names, you will mix up force and Force in no time.

Please check C# language documentation or go through some beginner C# tutorials.

https://www.youtube.com/watch?v=sQurwqK0JNE

2 Likes

Thank you, and I will try to learn the naming conventions :slight_smile: