- Home /
Array iteration problem
Hello, I have the following code:
for(int i = 0; i < slots; i++)
{
if(inventory[i] == GameObject.Find("Key"))
{
inventory[i] = null;
//inventory[i - 1] = null;
openDoor = true;
break;
}
}
This code iterates through an array to check if the player has the key, if the player does have the key, the index changes to a null value and the door is opened. The problem is, if the variable i is at 1 for example, and the player has the key, when inside the if statement the third element (2) is changed, instead of the second one (1).
I don't know if I'm making myself clear, and I apologize for my english. Thanks.
That shouldn't happen. How are you deter$$anonymous$$ing this is happening? Can you confirm the value of i at runtime?
print(i);
Something else is at play here.
I ran a bunch of tests on gameplay using Debug.Log, and I don't know why, but if I have the key in the index 0, the loop only enters the if statement on index 1, I know it doesn't make any sense, but this is what's happening :(
Well i assume it enters on index 1 because GameObject.Find will return null if it can't find that gameobject and i'm guessing index 1 is null?
Are you sure GameObject.Find("$$anonymous$$ey") is ever actually finding the object?
Also remember that GameObject.Find will search your hierarchy for that object, if the '$$anonymous$$ey' gets destroyed after being picked up it won't be able to find it. What happens to the $$anonymous$$ey once the player picks it up?
As I said before, I ran a bunch of tests, with various GameObjects in the array, but always with the key in it. If the key isn't in the array, the code simply ignores the if statement. When I do have the key in the inventory, the if statement is executed, but only one index later. After picking up the key I disable the mesh renderer of the object.
Wow... It worked... Can you explain why that line of code was the error? Thank you very much by the way :)
Answer by MissingSemicolon · Jun 27, 2013 at 03:47 PM
Maybe try altering the check so it looks for the name rather than the actual object and see what happens? e.g.
if(inventory[i].name == "Key")
Your answer
Follow this Question
Related Questions
Unity 3 GD HotShot-Tutorial Problem with an C#-Array 1 Answer
Saving 30 bools in an array possible? 2 Answers
C# Children and SubChildren Null Reference Exception 1 Answer
Inventory system using an array... 3 Answers
Distribute terrain in zones 3 Answers