I need help finding the index of an object in a list.
Hi, im trying to have it so that the script finds the current selected object, and then finds the index of that in an already made list. This is what I'm trying:
Transform currentSelection = Selection.activeTransform;
int currentSelectionIndex = myList.IndexOf (currentSelection);
The hope is that I would be able to affect the currently selected object with myList[currentSelectionIndex], but I can't get it to work.
Edit: The problem I'm getting is that everything I select (that's in the list) is saying the index is -1.
Did you check if Selection.activeTransform really returns something !null ? Just to check :)
Wow, didn't even think to check for that! $$anonymous$$y problem is happening before that, though. It says "error CS0103: The name `Selection' does not exist in the current context"
Edit: Realized I was missing using UnityEngine, just added that in. The problem I'm having now is that the currentSelectionIndex is returning as -1 for everything I select
Answer by SeasiaInfotechind · Nov 20, 2015 at 06:09 AM
HI jjesh,
List returns index to be -1 if it is not able to find that object in the given list. So your current selection object is not returning the data that is contained in list. It could be naming issue or anything. So please check that.
A sample script to show you that
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class abc : MonoBehaviour {
List<int> iList = new List<int>();
// Use this for initialization
void Start () {
iList.Add(2);
iList.Add(3);
iList.Add(5);
iList.Add(7);
}
// Update is called once per frame
public void ButtonClicked ()
{
int currentSelectionIndex = iList.IndexOf(7);
print (currentSelectionIndex);// It will return index 3
currentSelectionIndex = iList.IndexOf(9);
print (currentSelectionIndex);// it will give -1 as 9 is not present in the list.
}
}
I hope you find out whats getting wrong.
Thank you for your help! What I'm trying to do is find the gameobject which contains the input field I'm typing in, but it turns out how I was doing it was finding the gameobject i gad selected in the editor. Any idea how I would do this?
Hi, Your query is not very clear . Elaborate it
Your answer
Follow this Question
Related Questions
List update 0 Answers
Unknown Argument Out of Range Index Error On Card Game 1 Answer
Character Selection 0 Answers
How to output a List of Strings to canvas text? 0 Answers
How do I make something move for only a few seconds C# 1 Answer