[SOLVED] No 3 hit sprite, no spriteIndex on prefab inspector

So I’m using Unity 5 and MonoDevelop. Let’s get that out front.

public int maxHits;
private int timesHit;
private LevelManager levelManager;
public Sprite[] hitSprites;
public int spriteIndex;

// Use this for initialization
void Start () {
	timesHit = 0;
	levelManager = GameObject.FindObjectOfType<LevelManager>();
}

// Update is called once per frame
void Update () {
	
}



void OnCollisionEnter2D (Collision2D col)
{
	timesHit++;
	if (timesHit >= maxHits) {
		Destroy (gameObject);
	} else {
		LoadSprites();
		this.GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
	}
}

void LoadSprites () {
	int spriteIndex = timesHit - 1;
}

And that is my code. in the video, Ben instructs us to write this code:

this.GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];

When I write this, with the rest of the code Ben wrote, it tells me that spriteIndex is not valid. You can see that I have spriteIndex declared in the LoadSprites method.

This code would not work without publicly declaring the spriteIndex integer at the start of the class. I’m not sure why. From what I can tell, Ben doesn’t have it set up like this, but my code refused to acknowledge spriteIndex otherwise.

I’m starting to think I have something messed up.

Ben’s bricks aren’t asking for a Sprite Index and mine are.

Here’s my inspector on any of my prefab bricks:

Here’s Ben’s:

So if I recall correctly, the code Ben writes is specifically set so as to remove my requirement to set some of these attributes; Sprite Index being one of them.

What’s wrong here?

(I should note that the game is functioning perfectly EXCEPT the final sprite for the 3 hit brick doesn’t display. It displays sprite 2, but not the almost destroyed sprite 3.)

Aha!

} else {
	LoadSprites();
	this.GetComponent&lt;SpriteRenderer&gt;().sprite = hitSprites[spriteIndex];
}
}

void LoadSprites () {
int spriteIndex = timesHit - 1;
}

Should actually read:

	} else {
		LoadSprites();
	}
}

void LoadSprites () {
	int spriteIndex = timesHit - 1;
	this.GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
}

This fixes all my problems.

1 Like

Thanks for working this out. I had the same problem. It’s working now.

Privacy & Terms