Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- public class IconGenerator : MonoBehaviour
- {
- [SerializeField] int _textureSize = 256;
- [SerializeField] GameObject _targetObject;
- [SerializeField] Camera _iconCam;
- [SerializeField] Image _outputImage;
- [SerializeField] LayerMask _layerMask;
- [SerializeField] bool _destroyCopy = true;
- GameObject _copyObject;
- Bounds _objectBounds;
- RenderTexture _renderTex;
- IEnumerator _generateTextureCoroutine;
- private void Start() {
- _renderTex = new RenderTexture(_textureSize, _textureSize, 0);
- _iconCam.targetTexture = _renderTex;
- _iconCam.cullingMask = _layerMask;
- }
- public void OnClickGenerateIcon() {
- Debug.Log("Generating new icon");
- if (_copyObject != null)
- Destroy(_copyObject);
- _copyObject = Instantiate(_targetObject);
- SetCenterPoint();
- _copyObject.transform.SetParent(transform);
- _copyObject.transform.localPosition = -_objectBounds.center;
- _copyObject.transform.localRotation = Quaternion.identity;
- FitCameraToObjectBounds();
- int layer = LayerMask.NameToLayer("Icon Generator");
- SetLayerToChildren(_copyObject, layer);
- // start coroutine to generate a sprite from a texture
- if (_generateTextureCoroutine != null)
- StopCoroutine(_generateTextureCoroutine);
- _generateTextureCoroutine = GetSpriteFromTexture();
- StartCoroutine(_generateTextureCoroutine);
- }
- void SetCenterPoint() {
- MeshRenderer[] renderers = _copyObject.GetComponentsInChildren<MeshRenderer>();
- _objectBounds = new Bounds(_copyObject.transform.position, Vector3.zero);
- for (int i = 0; i < renderers.Length; i++) {
- _objectBounds.Encapsulate(renderers[i].bounds);
- }
- }
- void FitCameraToObjectBounds() {
- float maxSide = _objectBounds.size.z > _objectBounds.size.y ? _objectBounds.size.z : _objectBounds.size.y;
- _iconCam.orthographicSize = maxSide * 0.6f; // 0.5 will fit the icon perfectly, 0.6 to have some free space around the object
- }
- IEnumerator GetSpriteFromTexture() {
- yield return new WaitForEndOfFrame();
- Texture2D texture = RenderTextureToTexture2D(_renderTex);
- Sprite sprite = Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
- _outputImage.sprite = sprite;
- if (_destroyCopy)
- Destroy(_copyObject);
- }
- void SetLayerToChildren(GameObject targetObj, int layer) {
- targetObj.layer = layer;
- foreach(Transform child in targetObj.transform) {
- SetLayerToChildren(child.gameObject, layer);
- }
- }
- Texture2D RenderTextureToTexture2D(RenderTexture renderTex) {
- Texture2D destination = new Texture2D(renderTex.width, renderTex.height, TextureFormat.RGBA32, false);
- destination.Apply();
- Graphics.CopyTexture(renderTex, destination);
- return destination;
- }
- }
Advertisement
Advertisement
Advertisement
RAW Paste Data
Copied
Advertisement