2013-12-13 32 views
0

我一直在Unity3D的模擬器上工作,我需要一個客戶對象能夠以最低的價格自動查找商店對象。Unity3D:根據價格的自動目標

我對此做了一些測試,發現它很難達到目的。所以我希望有人能夠幫助我在正確的方向上進一步調整我的代碼? :)

下面的代碼到目前爲止我有:

var cityName : String; 
var shopScript : MarketScript; 


function FindShopPlace() : GameObject //Make a queueing system 
{ 
    var max : float; 
    var target : GameObject; 
    var gos : GameObject[]; 

    var goScript : MarketScript; 

    gos = GameObject.FindGameObjectsWithTag("market"); 

    for (var go : GameObject in gos) 
    { 
     goScript = go.GetComponent(MarketScript); 

     if (goScript.cityName == cityName) 
     { 
      if (goScript.resalePrice >= max && goScript.cityName == cityName) 
      { 
       max = goScript.resalePrice; 
      } 

      if (goScript.resalePrice < max && goScript.cityName == cityName) 
      { 
       print ("test"); 
       target = go; 
      } 
     } 
    } 
    shopScript = target.GetComponent(MarketScript); 
    return target; 
} 
與此代碼

目前,該目標是從來沒有發現和分配。

的NullReferenceException::未設置爲一個 對象ConsumerScript.FindShopPlace(的實例對象引用)(在 資產/ _MyAssets/_Scripts/ConsumerScript.js我從底部獲得由行號3以下的NullReferenceException: 268)ConsumerScript.Update ()(在資產/ _MyAssets/_Scripts/ConsumerScript.js:96)

回答

0

你得到一個NullReferenceException因爲目標從來沒有設置任何對象。

你在循環中做的是(1)找到最大價格和(2)找到最大值之後的最後一個對象,它小於最大值。

因此,如果您的價格按順序爲1,2,3,則目標將永遠不會被設置,因爲在每一步中您都將最大值設置爲新值,並且永遠不會設置目標值。即使設定它不一定是最便宜的。考慮價格的1,3,2

First Step: Set maximum to 1 
Second Step: Set maximum to 3 
Third Step: Set target to the GameObject with price 2 

如果你看到下面的錯誤嘗試像這樣簡單的例子去底層的東西。你也使用變量最大值(第一次比較),沒有設置任何東西,不知道這是否工作在Javascript(它可能),但它的不好的做法

你真的想要的是沒有找到最高價格或最低價格,但具有最低轉售價格的遊戲對象。

var min : float; 
var success : boolean; 
var firstHit : boolean; 


... 

success = false; 
firstHit = true; 

for (var go : GameObject in gos) 
{ 
    goScript = go.GetComponent(MarketScript); 

    if (goScript.cityName == cityName) 
    { 
     success = true; 

     if(firstHit) // alternatively to this would be to set minimum to a value that is higher than every possible price (thats also what i meant with you shouldnt use max without setting it to anything) 
     { 
      min = goScript.resalePrice; 
      target = go; 
     } 
     else 
     { 
      if (goScript.resalePrice < min) 
      { 
       min = goScript.resalePrice; 
       target = go; 
      } 
     } 
    } 
} 

if(success) 
{ 
    shopScript = target.GetComponent(MarketScript); 
    return target; 
} 
else 
{ 
    // TODO: handle the case that there isnt a shop in the city. 
    //  Maybe give an error Message with Debug.Log if this isnt supposed to happen 

    return null; 
} 
+0

你真棒!關於保持最低價值的訣竅使得更多的意識,我在幾分鐘內幫助你解決問題。我不能夠感謝你! :) –