Unity3D:代码中改变Sprite

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test2 : MonoBehaviour {
	public GameObject platform;

	// Use this for initialization
	void Start () {
		changeSpriteByAnotherSprite ();
	}

	void changeSpriteByImage(){
		Texture2D Tex = Resources.Load ("enter") as Texture2D;
		SpriteRenderer spr = platform.GetComponent<SpriteRenderer> ();  
		Sprite spriteA = Sprite.Create (Tex, spr.sprite.textureRect, new Vector2 (0.5f, 0.5f));
		platform.GetComponent<SpriteRenderer> ().sprite = spriteA;
	}

	void changeSpriteByAnotherSprite(){
		Sprite spriteB = Resources.Load<Sprite> ("test");
		platform.GetComponent<SpriteRenderer> ().sprite = spriteB;
	}
}

注意:必须将Sprite资源和Image放在Resources文件夹下面。

用changeSpriteByAnotherSprite()更方便,在编辑器中设置刚方便,注意Pixels Per Unit的设置。

posted @ 2017-05-18 12:18 MakeBetter 阅读(...) 评论(...) 编辑 收藏