- Home /
Problem with for... in loop
Hello :)
I need to have several tags on one object, so I used a solution I found online, which is to parent my object to an EmptyGameObject which has the tag on it and then let the code find the parent to that object.
My problem is that I always get an "enumerable" error when it comes to the "for... in" loop I'm using.
This is the script:
var curs : UI.Image;
public var sensedObjects : GameObject;
function Start () {
sensedObjects = GameObject.FindWithTag("ben");
}
function Update () {
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5,0));
//On Mouse Click: Pick up Objects with tag "eins" when looked at
if(Input.GetMouseButtonDown(0) && Physics.Raycast(ray, hit, 100) && hit.collider.gameObject.tag == "eins"){
Destroy(hit.transform.gameObject);
}
//Change cursor colour when looked at object has tag "eins"
if(Physics.Raycast(ray, hit, 100) && hit.collider.gameObject.tag == "eins"){
curs.color = Color(0.7,0.8,0.9,1);
} else {
curs.color = Color.white;
}
//Find Objects with Child tagged "ben" and change cursor colour when looked at
for (var foundOne : Transform in sensedObjects){
var objectMain = foundOne.transform.parent.gameObject;
if(Physics.Raycast(ray, hit, 100)){
Debug.Log("Look, there's something!");
curs.color = Color(0.7,0.8,0.9,1);
} else {
curs.color = Color.white;
}
}
}
I've tried replacing "Transform" with "GameObject", but it doesn't make a difference.
Does anyone know what to do or is there another way to solve my problem?
Thanks in advance ;)
Answer by Bonfire-Boy · Nov 26, 2015 at 11:49 AM
GameObject.FindWithTag returns a single GameObject, hence not enumerable.
It looks like you want to be using GameObject.FindGameObjectsWithTag.
Thank you :) Unfortunately now I get a "Cannot convert 'UnityEngine.GameObject[]' to 'UnityEngine.GameObject'." error :/
Because sensedObjects needs to be a GameObject[]...
GameObject.FindGameObjectsWithTag returns an array of GameObjects, so sensedObjects has to be an array of GameObjects (not a single GameObject like in your code).
Your answer
Follow this Question
Related Questions
How to correctly shorten this script using arrays and iterations 2 Answers
Android multitouch problem 1 Answer
change material in children 3 Answers
list.contains isn`t working 1 Answer
Unity Freezing 1 Answer