我试图标记所访问的对象列表。我是C#和编程的初学者。 所以我迭代一个对象列表,检查他们到一个平面的距离,然后我保存它们。但我需要检查该对象是否已被访问过..
问题在于visitTrees,我需要将它们保存在那里,以便在访问所有树对象时退出。
HashSet<Vector3> visitedTrees = new HashSet<Vector3>();
var stripes = new Dictionary<int, List<Transform>>();
int stripeNumber = 0;
cameraPlane.SetNormalAndPosition(normal, view.camera.transform.position + normal * minDistance);
int visited = 0;
while (true)
{
bool reachedFarTree = false;
foreach (var gameObject in trees)
{
float distance = cameraPlane.GetDistanceToPoint(gameObject.transform.position);
Debug.Log("distances " + Mathf.Abs(distance));
if (Mathf.Abs(distance) < 20)
{
List<Transform> treeStripes;
if (!stripes.TryGetValue(stripeNumber, out treeStripes))
{
treeStripes = new List<Transform>();
stripes[stripeNumber] = treeStripes;
}
treeStripes.Add(gameObject.transform);
if (!visitedTrees.Contains(gameObject.transform))
{
visitedTrees.Add(gameObject.transform.position);
visited++;
}
}
if (visited == visitedTrees.Count)
{
reachedFarTree = true;
}
}
offset += 20;
cameraPlane.SetNormalAndPosition(normal, view.camera.transform.position + normal * offset);
stripeNumber++;
if(reachedFarTree)
break;
}
答案 0 :(得分:1)
问题在于你实例化:
HashSet<Vector3> visitedTrees = new HashSet<Vector3>();
然后你尝试查找:
if (!visitedTrees.Contains(gameObject.transform))
其中gameObject.Transform的类型为Transform(一个Matrix),而HashSet只能包含Vector3对象。
取而代之的是:
HashSet<Transform> visitedTrees = new HashSet<Transform>();
或强>
if (!visitedTrees.Contains(gameObject.transform.position))
{
visitedTrees.Add(gameObject.transform.position);
visited++;
}
修改强>
HashSet<Vector3> visitedTrees = new HashSet<Vector3>();
var stripes = new Dictionary<int, List<Transform>>();
int stripeNumber = 0;
cameraPlane.SetNormalAndPosition(normal, view.camera.transform.position + normal * minDistance);
int visited = 0;
while (true)
{
bool reachedFarTree = false;
foreach (var gameObject in trees)
{
float distance = cameraPlane.GetDistanceToPoint(gameObject.transform.position);
Debug.Log("distances " + Mathf.Abs(distance));
if (Mathf.Abs(distance) < 20 + offset)
{
List<Transform> treeStripes;
if (!stripes.TryGetValue(stripeNumber, out treeStripes))
{
treeStripes = new List<Transform>();
stripes[stripeNumber] = treeStripes;
}
treeStripes.Add(gameObject.transform);
if (!visitedTrees.Contains(gameObject.transform.position))
{
visitedTrees.Add(gameObject.transform.position);
visited++;
}
}
}
if (trees.Count >= visited)
{
reachedFarTree = true;
}
offset += 20; // may try for a smaller value
cameraPlane.SetNormalAndPosition(normal, view.camera.transform.position + normal * offset);
stripeNumber++;
if (reachedFarTree)
break;
}