Niclas
Niclas

Reputation: 1402

Parameter can be IEnumerable - How to change code?

resharper says Parameter can be IEnumerable, for the parameter "gameObjects". How do I change the code to this, and what's the benefit of doing so?

Transform GetClosestObject (Transform[] gameObjects) {
    Transform bestTarget = null;
    float closestDistanceSqr = Mathf.Infinity;
    Vector3 currentPosition = transform.position;
    foreach(Transform potentialTarget in gameObjects) {
        Vector3 directionToTarget = potentialTarget.position - currentPosition;
        float dSqrToTarget = directionToTarget.sqrMagnitude;
        if(dSqrToTarget < closestDistanceSqr) {
            closestDistanceSqr = dSqrToTarget;
            bestTarget = potentialTarget;
        }
    }

    return bestTarget;
}   

Upvotes: 0

Views: 367

Answers (1)

sparkplug
sparkplug

Reputation: 1366

Resharper is telling you that you can change the gameObjects parameter to be of type IEnumerable rather than array. This results in a more flexible method signature as it allows the caller to input an array or List or other IEnumerable implementation.

See https://www.jetbrains.com/help/resharper/ParameterTypeCanBeEnumerable.Global.html

IEnumerable is found under the System.Collections.Generic namespace. To use, add

using System.Collections.Generic;

to the top of your file.

To fix your code, change

Transform GetClosestObject (Transform[] gameObjects) {

to

Transform GetClosestObject (IEnumerable<Transform> gameObjects) {

Upvotes: 3

Related Questions