DSCH
DSCH

Reputation: 2386

Unity - Affect only clicked GameObject

I am new to unity, and I tried to create a prefab for a tile in a game. So whenever a user clicks the tile it should change its sprite. The problem is that all the copies (instances) in my game are changing their sprite.

This is what I tried:

   void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject gameObject = this.gameObject;
            SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
            Sprite sprite = Resources.Load<Sprite>("Sprites/red");
            renderer.sprite = sprite;
        }
    }

What am I doing wrong? Thanks in advance

Upvotes: 0

Views: 640

Answers (2)

vasmos
vasmos

Reputation: 2586

Like akin said you are changing all sprites on a mouse click, you can raycast to your objects and check if they are hit then change it

Run this part on a script attached to your player or camera

void FixedUpdate()
{
    RaycastHit hit;

    if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0f)) {
if (hit.transform.gameObject.GetComponent<yourscript>()) {    
hit.transform.gameObject.GetComponent<yourscript>().ChangeSprite();
        }
}
}

attach to tile game objects

public class yourscript : MonoBehaviour

{

public void ChangeSprite() {
            SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
            Sprite sprite = Resources.Load<Sprite>("Sprites/red");
            renderer.sprite = sprite;
}

}

Upvotes: 1

S&#233;rgio Carneiro
S&#233;rgio Carneiro

Reputation: 3966

You are detecting if the mouse button is pressed, not if it's pressed over the given tile.

There are several ways to do it, but I would say the standard way is to:

  1. Attach a Collider to the GameObject
  2. Implement OnMouseDown
void OnMouseDown()
{
     GameObject gameObject = this.gameObject;
     SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
     Sprite sprite = Resources.Load<Sprite>("Sprites/red");
     renderer.sprite = sprite;
}

Upvotes: 4

Related Questions