Trabla: Unity3D: get game object SpriteRenderer
Solving:
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Example:
using UnityEngine;
using System.Collections;
public class ChangeSpriteByClick: MonoBehaviour {
// this public fields appears in unity editor - so simply drag sprites to fields
public Sprite firstSprite = null;
public Sprite secondSprite = null;
// Use this for initialization
void Start () {
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
renderer.sprite = firstSprite;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
Debug.Log("Pressed left click.");
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
if( renderer.sprite == firstSprite ){
renderer.sprite = secondSprite;
}else{
renderer.sprite = firstSprite;
}
}
}
}
No comments:
Post a Comment