Tanoda
Pool.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System;
10using System.Collections.Generic;
11using UnityEngine;
12
13namespace Leap.Unity {
14
19 public interface IPoolable {
20 void OnSpawn();
21 void OnRecycle();
22 }
23
66 public static class Pool<T> where T : new() {
67 [ThreadStatic]
68 private static Stack<T> _pool = new Stack<T>();
69
70 public static T Spawn() {
71 if (_pool == null) _pool = new Stack<T>();
72
73 T value;
74 if (_pool.Count > 0) {
75 value = _pool.Pop();
76 } else {
77 value = new T();
78 }
79
80 if (value is IPoolable) {
81 (value as IPoolable).OnSpawn();
82 }
83
84 return value;
85 }
86
87 public static void Recycle(T t) {
88 if (t == null) {
89 Debug.LogError("Cannot recycle a null object.");
90 return;
91 }
92
93 if (t is IPoolable) {
94 (t as IPoolable).OnRecycle();
95 }
96
97 _pool.Push(t);
98 }
99
101 public static void Recycle(T t0, T t1) {
102 Recycle(t0); Recycle(t1);
103 }
104
106 public static void Recycle(T t0, T t1, T t2) {
107 Recycle(t0); Recycle(t1); Recycle(t2);
108 }
109
111 public static void Recycle(T t0, T t1, T t2, T t3) {
112 Recycle(t0); Recycle(t1); Recycle(t2); Recycle(t3);
113 }
114
115 }
116}
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
Implement this interface to recieve a callback whenever your object is spawned from a pool.
Definition: Pool.cs:19