我一直在使用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;
}
目前使用此代码,永远不会找到并分配目标。我从底部的第3行得到以下NullReferenceException:
NullReferenceException:未将对象引用设置为的实例 对象ConsumerScript.FindShopPlace()(at Assets / _MyAssets / _Scripts / ConsumerScript.js:268)ConsumerScript.Update ()(在Assets / _MyAssets / _Scripts / ConsumerScript.js:96)
答案 0 :(得分:0)
您会收到NullReferenceException,因为target从未设置为任何对象。
你在循环中做的是(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
如果您遇到这样的错误,请尝试使用这样的简单示例来深入了解问题。你也使用变量maximum(比较第一次)而没有将它设置为任何东西,不确定这是否适用于Javascript(可能),但它的不良做法
您真正想要的不是找到最高价格或最低价格,而是具有最低转售价格的GameObject。
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;
}