- Home /
Error assigning to a variable
How could I get around this problem?
Assets/Chat/Chat.cs(140,25): error CS1656: Cannot assign to `entry' because it is a 'foreach iteration variable'
foreach(string entry in scrollingNotices) {
GUILayout.BeginHorizontal();
entry = GUILayout.TextField(entry);
Basically, it's not possible to assign value to foreach iteration variables. Please close two duplicates of this question, and then I'll try to provide more help.
I don't really understand the previous answer. The main problem is not necessarily that it is readonly, I don't know about that. The real issue that the compiler is saving you from is that when you use a foreach loop, the variables of that loop are passed by copy. You'll need to access the variable in the scrollingNotices that contains that particular entry and modify it directly.
Actually it is readonly. Internally, foreach uses IEnumerator, calling its $$anonymous$$oveNext method and accessing current element with Current property, which is readonly.
Elements are not passed by copy as well, because if they were, then modification of properties/fields of non-primitive types would be visible inside foreach scope only.
And besides, if they were passed as copies, then everybody would use foreach as a perfect deep cloner :)
I believe the reference to the object is a copy. I could be wrong. But! I did not mean that the whole object was copied. That wouldn't make sense for a reference object. Having a copied reference to the object, you can still set variables of the object, and that still modifies the object whose reference was copied. But, changing the copied reference to point to a different reference, that does not modify the original object.
Ok - I misunderstood you then, because I thought you were referring to copying the whole object.
Answer by aldonaletto · Sep 10, 2013 at 01:01 PM
The variable entry is readonly: it's assigned internally only by the foreach code, and you can't modify it. If you really want to allow edition of scrollingNotices elements via GUI, the code must be something like this:
for (int i=0; i<scrollingNotices.Length; i++){
GUILayout.BeginHorizontal();
scrollingNotices[i] = GUILayout.TextField(scrollingNotices[i]);
...
But if you just want to display the elements of scrollingNotices, keep your original code and use GUILayout.Label instead:
foreach (string entry in scrollingNotices) {
GUILayout.BeginHorizontal();
GUILayout.Label(entry);
...
Your answer
Follow this Question
Related Questions
Error assigning to a variable 0 Answers
Error assigning to a variable 0 Answers
Targeting Issue Error 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers