- Home /
for loop error
In my Inventory script (with #pragma strict turned on) I Get the error Cannot convert 'Object' to 'UnityEngine.GameObject'.
var items : List.;
function OnGUI () {
for (var item : GameObject in items) { //error here I have gone everywhere but no one seems to have encountered this.
The code you posted will compile and run without any errors. The reason no one has encountered any problem with this is because there isn't any. I would guess you actually have different code that's creating a problem.
I'll update the question now, with a more helpful list of problematic and complicated code =D
You need to listen to the errors you get; your code generates plenty of errors that aren't the one you gave us:
Take out the parentheses after var items : List.
items.Add(LOWERCASE I HERE)
$$anonymous$$ost importantly, you didn't define DropAndDrag.
After those things are taken care of, there are no longer any errors. This code is useless to us, and so doesn't help you get your question answered. You need to spend some time learning how to cut down on what is irrelevant, so you can move forward.
Please try to understand what you are saying. You post us snippets that don't compile, and don't yield the error you mentioned. That is useless.
when I did what you guys said to do with the for loop, it didn't work. And then I got the error for sending a message. $$anonymous$$y question was not at all, put across well and for that I am sorry.
Answer by MithosAnnar · Mar 06, 2012 at 03:33 PM
The correct and simple answer is this:
for (var item in items) {
(item as GameObject).SendMessage("Activate");
}
I decided to come back to this after a while. And it took me an hour and a half but this is what works. Jessy and Eric5h5, thank you both so much for helping me to get the correct answer.
Answer by Jessy · Feb 22, 2012 at 05:41 PM
http://unity3d.com/support/documentation/ScriptReference/GameObject.GetComponent.html
http://unity3d.com/support/documentation/Manual/Generic%20Functions.html
var i = item.GetComponent.<Item>();
which is a shorthand for
var i = item.GetComponent(Item) as Item;
There is tons of information on this on Unity Answers and the forum.
I already fixed the item.GetComponent problem I was having, with:
i.Send$$anonymous$$essage ("DragAndDrop");
But I still can't figure out the for loop error.
I never saw anything about Send$$anonymous$$essage (which I do not recommend using).
In Unityscript you should use var i = item.GetComponent(Item);
. It's faster than the generic version, and less ugly. There's no reason to use var i = item.GetComponent(Item) as Item;
. The only reason you'd use casting is if you were using a string in GetComponent, so that it was forced to return Component ins$$anonymous$$d of the type. (No, the docs still have not been updated with the correct info, even though this has been the case since Unity 3.4....)
Eric, you ought to make that an answer; you know UnityScript better than anybody, I think.