- Home /
C# List For Loop Only Returns Last Element
I have a script that creates a list of all the gameobjects the scripted gameobject has collided with. OnMousedown it's suppose to check through all the obstacles.transform.positions and make sure transform.position does not equal any of them. However only the last element is being read so the if statement is true whereas it should run through all of the gameobjects within obstacles and return back false. Is there something wrong with my logic?
using UnityEngine;
using System.Collections.Generic;
public class AssignTargetPositionScript : MonoBehaviour {
public Vector3 targetPosition;
public List <GameObject> obstacles = new List<GameObject>();
void Update ()
{
if(Input.GetMouseButtonDown(0)){
for(int i = 0; i < obstacles.Count; i++){
if(transform.position != obstacles[i].transform.position){
targetPosition = transform.position;
}
}
}
}
void OnTriggerEnter2D(Collider2D other) {
obstacles.Add(other.gameObject);
}
void OnTriggerExit2D(Collider2D other) {
obstacles.Remove(other.gameObject);
}
}
I don't think it's the list that's the problem - it's the logic in your Update loop, which states:
"(When I click the mouse button), look through the list of obstacles, and for every obstacle I encounter that's not at the position of this script, move the target position to the position of this script."
I'm really unclear from that what you're trying to achieve?
I've started a project and this is the only script I've started working on. For right now I'm just trying to figure out how to detect gameobjects with colliders, sort them into obstacles and make sure that the scripted gameobject cannot be in any of the same positions as said obstacles. Part of me is wondering if I going about this the wrong way. It seemed straight forward enough to me at first.
Not sure if this is what you want, but do you want to find ALL objects with 2d colliders?
http://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
Also, have you looked into Bounds.Overlaps()? (I may have misspelled that function name)