CustomComponent.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Component, Node, find, __private, AssetManager, assetManager, Prefab, instantiate, UITransform } from "cc";
  2. import { EDITOR } from "cc/env";
  3. import { Debug } from "../util/Debug";
  4. const Tag: string = 'Component'
  5. if (!EDITOR) {
  6. Component.prototype.findNode = function (path: string, referenceNode?: Node): Node {
  7. if (!referenceNode) referenceNode = this.node
  8. return find(path, referenceNode)
  9. }
  10. Component.prototype.findComp = function <T extends Component>(path: string, comp: __private.__types_globals__Constructor<T> | __private.__types_globals__AbstractedConstructor<T>, referenceNode?: Node): T {
  11. if (!referenceNode) referenceNode = this.node
  12. const n: Node = find(path, referenceNode)
  13. return n?.getComponent(comp)
  14. }
  15. Component.prototype.instantiate = async function (bundleName: string, path: string, parent?: Node): Promise<Node> {
  16. return new Promise<Node>((resolve, reject) => {
  17. if (!parent) parent = this.node
  18. const bundle: AssetManager.Bundle = assetManager.getBundle(bundleName)
  19. if (!bundle) {
  20. Debug.Warn(Tag, `bundle ${bundleName} not exist or loaded`)
  21. reject()
  22. return
  23. }
  24. const startTime: number = Date.now()
  25. const prefab: Prefab = bundle.get(path, Prefab)
  26. let node: Node = null
  27. if (prefab) {
  28. node = instantiate(prefab)
  29. parent.addChild(node)
  30. Debug.Log(Tag, `prefab ${path} instantiate success, cost ${Date.now() - startTime} ms`)
  31. resolve(node)
  32. } else {
  33. bundle.load(path, Prefab, (err, prefab) => {
  34. if (err) {
  35. reject()
  36. } else {
  37. if (!this.isValid) return
  38. node = instantiate(prefab)
  39. parent.addChild(node)
  40. Debug.Log(Tag, `prefab ${path} instantiate success, cost ${Date.now() - startTime} ms`)
  41. resolve(node)
  42. }
  43. })
  44. }
  45. })
  46. }
  47. Object.defineProperty(Component.prototype, 'uiTrans', {
  48. get: function () {
  49. return this.node.getComponent(UITransform)
  50. }
  51. })
  52. }