我有此代码:
if(car.position == a1.position)
{
car.speed = 0;
a1 = 1;
if(cooldow == 0){
car.taget.position = targetHere.position
car.speed = 5;
a1 = 0;
Destroy(obj, 5)
}
}
第一个条件[if(car.position == a1.position)]我将重复10次以上,这意味着我将检查(car.position)是否与 a2.position < / strong>,然后是 3.position ,然后是 a4.position ,然后是 a5.position ,然后是 a6.position 然后是< strong> b1.position ,然后 b2.position ,然后 b3.position ,然后 b4.position ,然后 b5.position < / strong>然后 b6.position ....十二次...,我找不到将其放入( For )循环。
任何想法如何做到!!! TY
答案 0 :(得分:2)
我假设a1是一个变换,因为您正在访问它的位置变量。我还假设您是在检查器中分别分配这些游戏对象。
我会执行以下操作:
// Make sure to put all your a objects in this list in the inspector
public List<Transform> myABCObjects;
void CheckPositions()
{
// This foreach loop, will loop through your list of transforms, so your a b c
// objects would be added to this list via the inspector, or through whatver
// code you are using to set them.
foreach(Transform a in myABCObjects)
{
// Not to sure if you can do an == on a vector3, but I wouldn't want to
// considering the data members are float, and can cause floating point error
// Because of this I am getting the distance to the location, and using
// Mathf.Approximately to check if the distance is close to 0f.
if(Mathf.Approximately(car.position.distance(a.position), 0f))
{
// Your logic here if location is the same...
// so if you are trying to remove say a1
// add this object to a list, to be removed after the loop
// then continue on.
}
}
// if you are removing an object, check the list size, then loop through it to remove the objects from your original list...
}
使用for循环而不是foreach的示例:
// Make sure to put all your a objects in this list in the inspector
public List<Transform> myABCObjects;
void CheckPositions()
{
// This for loop, will loop through indices 0 - myABCObjects.count - 1, so your a b c
// objects would be added to this list via the inspector, or through whatver
// code you are using to set them.
for(int i = 0; i < myABCObjects.count; ++i)
{
// Not to sure if you can do an == on a vector3, but I wouldn't want to
// considering the data members are float, and can cause floating point error
// Because of this I am getting the distance to the location, and using
// Mathf.Approximately to check if the distance is close to 0f.
if(Mathf.Approximately(car.position.distance(myABCObjects[i].position), 0f))
{
// Your logic here if location is the same...
}
}
}
答案 1 :(得分:1)
如果[a1..a6]和[b1..b6]具有相同的类型,则尝试这样做:
var list = new List<TypeOfa1> {a1, a2, a3, a4, a5, a6, b1, b2, b3, b4, b5, b6};
foreach (var item in list)
{
if (car.position == item.position)
{
car.speed = 0;
item = 1;
if (cooldow == 0)
{
car.taget.position = targetHere.position;
car.speed = 5;
item = 0;
Destroy(obj, 5);
}
}
}
答案 2 :(得分:0)
您可以创建变量的集合,然后通过它们运行foreach。
List<CarType> collection = new List<CarType> {a1, b1, a2, b2 ...};
foreach (CarType c in collection)
{
// do stuff
}