Find with string concatenation
I have troubles doing un a GameObject.Find a string concatenation in a for syntax.
This is my code:
GameObject gridSlot;
for(int i = 1; i < combatSize && mEnemySlot == null; i++) {
string s = "slot_" + i + '_' + col;
gridSlot = GameObject.Find(s);
if(gridSlot != null) {
if(gridSlot.transform.childCount > 0) {
mEnemySlot = gridSlot;
Debug.Log("Enemy slot: " + gridSlot.name);
}
}
}
For example, if I put directly string s = "slot_1_4" then code works fine. What's wrong in my code? How can I put the concatenation to have the code works?
Thanks!
From the snippet you posted, the variable col
goes unassigned, so it's difficult to tell if that's the reason your find fails or if it's something else. As written, even if col has a value that points to some object in your scene, I'd wager the loop only gets one pass, because it'll ter$$anonymous$$ate as soon as mEnemySlot is assigned a value. Assu$$anonymous$$g of course gridSlot is found and it has children. Hard to tell without seeing the Hierarchy.
@Vicarian it's assiged to an int. I try with a string but return the same, not works fine
The next issue is mEnemySlot having a value. If it does, then the loop never is entered, or it enters once, assigns a value to mEnemySlot and then ter$$anonymous$$ates on the next pass. It's the second conditional of your for loop : i < combatSize && mEnemySlot == null
. You can check to see if mEnemySlot obtains a value by checking if it's not null and printing a debug statement.
Hi @Vicarian, it's a fragment of code. You can assum all variables are correctly initialized and code works fine with all loops. The problem it's on GameObject.Find If I put a single string, it return a correct GsmeObject, otherwise if I try with the code I put, (the string makes with variables i and col) then never return a valid GameObject
@neon_pc did you ever find out how this can work? having the exact same situation. if i hardcode the string it works, but a concatenated doesnt
Hello @aduijs I don't remember very well because in the end, I had change this code. If I'm not mistaken, I think the problem was the "col" variable wasen't works fine because their definition.
This code should be fine:
string[] slotPosition = new string[2];
slotPosition = slotId.Split('_');
int row = int.Parse(slotPosition[0]);
int col = int.Parse(slotPosition[1]);
mTargetSlot = GameObject.Find("slot_"+row+"_"+col);
Where slotid is a "GameObject.name" passed from the function
Your answer
Follow this Question
Related Questions
How to get the active/loaded Scene then turn the name of it into a string? [C#] 1 Answer
how to see if two string are the same (I just what to see if Magicsetom[x] is == to boxadd ) 2 Answers
Changing GUI Text to int and applying operands 1 Answer
Display string in the UI text in specific format 1 Answer
Error FormatException: Input string was not in a correct format. 0 Answers