0
\$\begingroup\$

I am making a game where the player mines dirt by walking on it: Too many squares So, I created a scene and added a bunch of dirt to a grid, from a dirt prefab. When the character walks on a square, it is supposed to change to dark dirt. If I only have a few hundred dirt squares, it works as expected. I step on the dirt, and it turns dark. But now that I have a few thousand dirt squares, unity renders incorrectly, and will only change the sprite for dirt squares that are in every 4 or 5 columns. See the following picture: Wrong Mining

The debugger outputs GetComponent<SpriteRenderer>().sprite.name for the dirt I walk on is DarkDirt even though it is showing up as "Dirt" in reality. The inspector in the scene view agrees that it should be rendering DarkDirt.

How can I get unity to re-draw sprites when they update?

\$\endgroup\$
  • \$\begingroup\$ I don't think your diagnosis of this issue is correct. I suspect that you're not holding a reference to the particular sprite you think you are - still referring to the earlier sprite that's already switched to dark dirt, when you think it should be pointing to an adjacent sprite. Try showing us how you're selecting the sprites to change. Aside from that though, rendering thousands of separate sprite renderers is not a suitable solution to this problem. You should look at using a Tilemap instead, or a single quad with a shader that draws the light or dark tiles according to an index texture. \$\endgroup\$ – DMGregory Feb 8 at 3:20
  • \$\begingroup\$ I am not using tiles, just sprites. I click the play button; walk on the dirt; click "scene view"; click on the dirt square I walked on. In the inspector it says DarkDirt, in the SpriteRenderer, but its actually showing up as the Dirt Sprite. I programatically select the dirt via Physics2D.OverlapPoint(position). It succeeds in finding the dirt. I will look into your idea about shader rendering a quad with an index texture. It sounds promising. \$\endgroup\$ – Caleb Feb 8 at 3:30
  • 2
    \$\begingroup\$ Sounds like you have multiple sprites overlapping, visually, in physics, or both \$\endgroup\$ – DMGregory Feb 8 at 3:34
0
\$\begingroup\$

Make sure that the tiles are not overlapping, and create a script similar to this.

public SpriteRenderer sr;

public Sprite light;
public Sprite dark;

void Start() {
   sr = GetComponent<SpriteRenderer>();
   sr.sprite = light;
}

void OnCollisionEnter2D(Collider2D other)
{
   if (other.tag==“Player”)
   {
      sr.sprite = dark;
   }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.