Noobie
Noobie

Reputation: 55

How can I return a float from a function with different type arguments?

I have this function and I want to pass two Vector3 arguments and one int so I can return a float value. How can I return a float value even tho I use Vector3 and int as arguments? This is my code:

//find other types of distances along with the basic one
public object  DistanceToNextPoint (Vector3 from, Vector3 to, int typeOfDistance)
{
    float distance;
    //this is used to find a normal distance
    if(typeOfDistance == 0)
    {
        distance = Vector3.Distance(from, to);
        return distance;
    }
    //This is mostly used when the cat is climbing the fence
    if(typeOfDistance == 1)
    {
       distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z));
    }
}

When i replace the "object" keyword with the "return" keyworkd it gives me this error; enter image description here

Upvotes: 1

Views: 2420

Answers (3)

Soenhay
Soenhay

Reputation: 4048

Two problems with your code.

  1. If you want to return an object type then you need to cast your result to float before using it.
  2. Not all code paths return a value.

You can try this:

/// <summary>
/// find other types of distances along with the basic one
/// </summary>
public float DistanceToNextPoint (Vector3 from, Vector3 to, int typeOfDistance)
{
    float distance;

    switch(typeOfDistance)
    {
        case 0:
             //this is used to find a normal distance
             distance = Vector3.Distance(from, to);
        break;
        case 1:
             //This is mostly used when the cat is climbing the fence
             distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z));
        break;
    }

   return distance;
}

The changes include:

  • Return float type instead of object
  • Make sure all code paths return a float type
  • Reorganize to use a switch

Upvotes: 5

Pablo Exp&#243;sito
Pablo Exp&#243;sito

Reputation: 162

You should change the return type object to float.

    //finde other tipe of distances along with the basic one
    public float DistanceToNextPoint (Vector3 from, Vector3 to, int tipeOfDistance)
    {
        float distance;
        //this is used to find a normal distance
        if(tipeOfDistance == 0)
        {
            distance = Vector3.Distance(from, to);
            return distance;
        }
        //This is mostly used when the cat is climbing the fence
        if(tipeOfDistance == 1)
        {
           distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z))
           return distance;
        }
    }

Upvotes: 2

Ludovic Feltz
Ludovic Feltz

Reputation: 11916

just change return type from object to float like this:

public object  DistanceToNextPoint(...)

To:

public float  DistanceToNextPoint(...)

then return your variable distance in the last line of your method:

public float DistanceToNextPoint(...){
    // ...
    return distance:
}

Upvotes: 2

Related Questions