KaiClavier

STMCustomUIEvent.cs

Dec 25th, 2020
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. //Copyright (c) 2016-2020 Kai Clavier [kaiclavier.com] Do Not Distribute
  2. using UnityEngine;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5.  
  6. /*
  7. Example script for spawning a gameObject at a position on a Canvas.
  8. */
  9.  
  10. [RequireComponent(typeof(SuperTextMesh))]
  11. public class STMCustomUIEvent : MonoBehaviour
  12. {
  13.     public SuperTextMesh superTextMesh;
  14.     public GameObject spawnThisPrefab;
  15.     public string customTag = "spawn";
  16.     private List<GameObject> spawnedPrefabs = new List<GameObject>();
  17.     //set up STM initially
  18.     public void Reset()
  19.     {
  20.         superTextMesh = GetComponent<SuperTextMesh>();
  21.     }
  22.     //assign custom event
  23.     public void OnEnable()
  24.     {
  25.         superTextMesh.OnCustomEvent += CustomEvent;
  26.         superTextMesh.OnRebuildEvent += ClearAllObjects;
  27.     }
  28.     //unassign
  29.     public void OnDisable()
  30.     {
  31.         superTextMesh.OnCustomEvent -= CustomEvent;
  32.         superTextMesh.OnRebuildEvent -= ClearAllObjects;
  33.     }
  34.     public void CustomEvent(string text, STMTextInfo info)
  35.     {
  36.         if(text == customTag)
  37.         {
  38.             SpawnObject(text, info);
  39.         }
  40.     }
  41.  
  42.     private GameObject cachedNewObject;
  43.     public void SpawnObject(string text, STMTextInfo info)
  44.     {
  45.         //spawn a copy of the gameobject
  46.         cachedNewObject = Instantiate(spawnThisPrefab);
  47.         //set parent
  48.         cachedNewObject.transform.SetParent(superTextMesh.t);
  49.         spawnedPrefabs.Add(cachedNewObject);
  50.         //set position, rotation, and scale to be relative to text.
  51.         cachedNewObject.transform.position = superTextMesh.t.TransformPoint(info.Middle); //make relative to transform
  52.         cachedNewObject.transform.localRotation = spawnThisPrefab.transform.localRotation; //copy from prefab
  53.         cachedNewObject.transform.localScale = spawnThisPrefab.transform.localScale;
  54.     }
  55.     public void ClearAllObjects()
  56.     {
  57.         foreach(GameObject obj in spawnedPrefabs)
  58.         {
  59.             Destroy(obj);
  60.         }
  61.         spawnedPrefabs.Clear();
  62.     }
  63. }
  64.  
Add Comment
Please, Sign In to add comment