2017-10-05 3 views
1

私はこの関数を持っています.2つのVector3引数と1つのintを渡したいので、float値を返すことができます。私は引数としてVector3とintを使用してもfloat値を返すことができますか? これは私のコードです:私はkeyworkd「戻る」と「オブジェクト」のキーワードを交換するときタイプ引数が異なる関数から浮動小数点数を返すにはどうすればよいですか?

//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)); 
    } 
} 

それは私にこのエラーが発生します。 enter image description here

+5

宣言や 'return distance;'で 'object'を' float'に変更することができます。 –

+0

はい、すべての答えとコメントは答えを指します;) –

答えて

5

コードに2つの問題があります。

  1. オブジェクト型を返す場合は、結果をfloatにキャストしてから使用する必要があります。
  2. すべてのコードパスが値を返すわけではありません。

あなたはこれを試すことができます。

/// <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; 
} 

変更が含まれます:

  • を確認してください代わりに、オブジェクトの

    • 戻りfloat型のすべてのコードパスがfloat型
    • 再編成に戻りますスイッチを使用する場合
  • +0

    あなたの答え、短く、ポイント、そしてコードをより効果的にする方法をありがとう。 – Noobie

    2

    ちょうどこのようobjectからfloatに戻り値の型を変更します。あなたのメソッドの最後の行では、あなたの変数distanceを返し、その後

    public float DistanceToNextPoint(...) 
    

    :へ

    public object DistanceToNextPoint(...) 
    

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

    ありがとう、良い答え! – Noobie

    2

    returnタイプobjectfloatに変更する必要があります。

    //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; 
         } 
        } 
    
    関連する問題