- Home /
How to use spriteRenderer.sprite for a GameObject in a list?
I have a grid containing sprites and once I click one I have it change its sprite. However I would simultaneously want to change the sprite next to it. The way I thought to do this was by creating a list of the instantiated objects so I can access them later.
public void OnMouseDown()
{
ChangeTheSprite ();
}
public void ChangeTheSprite(){
itemlist = GetComponent<BoardManager> ();
if (spriteRenderer.sprite == redLight) {
spriteRenderer.sprite = greenLight;
// Here I try to change another sprite
itemlist.redLightList[1].GetComponent<SpriteRenderer> ().sprite = greenLight;
}
else {
spriteRenderer.sprite = redLight;
}
}
(for the example I'm simply changing the sprite on the 2nd grid location, the "next to it" will come later, though I suspect that it might become a problem as well as I don't know how to get the position of an object obtained with OnMouseDown in a list)
What am I doing wrong here?
Edit: huh.. Overread the sentence at the bottom of your Question :)
You could add a simple, clean script to each Object with only two public int variables for the row number and the number within a row (All sprites of one row are it's childs). Then while initializing the whole system (See below) you'd adjust the number to match the position inside the row. So you'd run a counter while iterating (foreach) over the childs of a row, keeping the counter the same number as the position within the list.
When you click, you only need to access the script, read the both int and there is your position.
Initialization:
Generate a list for each row and then create a parent list that contains all rows.
Like this you could first access the row and then the position of the sprite. If you now want to change the sprite beside, you'd only need increment/decrement the row number by 1
(Pseudo $$anonymous$$atrix style :) )
Row 1: Seat1, Seat2, Seat3, Seat4
Row 2: Seat1, Seat2, Seat3, Seat4
Row 3: Seat1, Seat2, Seat3, Seat4
Row 4: Seat1, Seat2, Seat3, Seat4
List[0][0] is Seat 1 in row 1
List[1][0] is Seat 1 in row 2
List[1][4] is Seat 4 in row 2
and so on...
Should give you an idea on how to do it. Didn't test it though :)
Yes. I ended up starting from scratch and have a bool for each item. All the items are placed in a array so I can easily access the right one. I even have my alpha of the game now but do not really have the time to continue. Thanks for your interest however!
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Sprite Mask Render Issue 1 Answer
Why do my GameObjects have a flickering line above them? 2 Answers
My gameObject is invisible 0 Answers