I have an object (TestObj) and I want to change its sprite from sprite1 to sprite2 when it's clicked on. How would I code that in C#?
You want to do this? Code (csharp): public Sprite sprite1, sprite2; // Sprites private SpriteRenderer spriteRenderer; void Start () { spriteRenderer = gameObject.GetComponent<SpriteRenderer> (); } void OnMouseDown () { if (spriteRenderer.sprite == sprite1) { spriteRenderer.sprite = sprite2; } else { spriteRenderer.sprite = sprite1; } }
Create a new game object. Drag your sprites into that gameobject in the hierarchy. Create a script along these lines: Code (csharp): public class ClickToChange : MonoBehaviour { public GameObject sprite_1; public GameObject sprite_2; void Awake() { // just to ensure a clean start. sprite_1.SetActive(true); sprite_2.SetActive(false); } void OnMouseDown() { sprite_2.SetActive(!sprite_2.activeSelf); sprite_1.SetActive(!sprite_1.activeSelf); } } You can then place your script and collider on that game object, and the add the references in the inspector. Not very fancy, but will do the trick. Cheers.