Finding an object's list index via the object's attached script
I have a List of cards in hand, set up in my Card Location Manager script.
List<GameObject> hand;
and I have a "Draggable" script attached to my cards to let you move them around. What I want is to get the index of the card I'm picking up when I drag it to, say, the play area.
int grabIndex = cardLocationManager.hand.IndexOf(this.gameObject);
This throws a NullReferenceException. This seems to be due to a distinction in GameObject vs gameObject, but I don't see how to resolve it. Having a List of all the cards currently in each location of the game (hand, play area, discard, deck) seems really useful for all kinds of stuff - allowing random draws, keeping track of card counts, and so on - but I've got to be able to get object index during player interaction or I can't keep it organized once the player's doing...anything.
Answer by muckenhoupt · Sep 25, 2020 at 11:50 PM
First, there's nothing wrong in the code you're showing us. Something isn't getting set up right beforehand. If it's throwing a NullReferenceException, it's trying to access a property or method of a variable, but can't, because the variable is currently null, and null doesn't have any properties or methods. There are three variables that you're accessing properties/methods of: cardLocationManager, cardLocationManager.hand, and this. It's really unlikely to be this; I'm not sure it's even possible for this to ever be null. So, my advice to you is: Check to see if cardLocationManager is null, and if it isn't, check to see if cardLocationManager.hand is null. Then try to figure out why the code that's supposed to be setting it to something other than null isn't being executed. (Possibly the reason is that you haven't written it yet. That happens sometimes.)
Holy crap. I was SO SURE cardLocation$$anonymous$$anager was properly set up because I use it so many other places - but those other places were other scripts, where it was properly set up. "Check to see if cardLocation$$anonymous$$anager is null" was the actual solution. It was, I initialized it in the Start method, and just like that everything works.
Thank you! I'd assumed my syntax on the IndexOf() method was incorrect because I'd never used it before, but I couldn't figure out how (because the problem was more basic than that). The reassurance that that part of the code was okay helped a lot.
Your answer
Follow this Question
Related Questions
[ANSWERED] IndexOf and LastIndexOf both returning -1 when an item is on the list. 1 Answer
Trying to get the index of a gameObject in a list 0 Answers
C# Having troubles with creating/referencing a random list. 1 Answer
Get every possible combination of elements in a list 1 Answer
How could I populate a list with a gameObject during runtime? 0 Answers