-
Notifications
You must be signed in to change notification settings - Fork 29
/
ObjectPool.cs
77 lines (71 loc) · 2.88 KB
/
ObjectPool.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Grass
{
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class ObjectPool : MonoBehaviour
{
public static List<GameObject> gameObjects = new List<GameObject>();
public static PhysicMaterial material;
//When removing from the list, use removeAt(count - 1) to avoid big CPU time reordering the list
//Return by just using .Add()
//I hate optimization I've been at it for days
void Awake()
{
GameObject.DontDestroyOnLoad(this);
}
void Start()
{
ObjectPool.material = new PhysicMaterial();
ObjectPool.material.dynamicFriction = 0.9f;
ObjectPool.material.staticFriction = 0.9f;
ObjectPool.material.frictionCombine = PhysicMaterialCombine.Maximum;
ObjectPool.material.bounciness = 0;
ObjectPool.material.bounceCombine = PhysicMaterialCombine.Average;
for (int i = 0; i < 250; i++)
{
GameObject go = new GameObject();
MeshCollider comp = go.AddComponent<MeshCollider>();
comp.sharedMaterial = ObjectPool.material;
go.AddComponent<AutoDisabler>();
//go.AddComponent<MeshRenderer>();
//go.GetComponent<MeshRenderer>().material = new Material(Shader.Find("Standard"));
//go.AddComponent<MeshFilter>();
go.SetActive(false);
GameObject.DontDestroyOnLoad(go);
gameObjects.Add(go);
}
}
public static GameObject FetchObject() //Has components? Return true. If the object was instantiated instead, return false
{
if (gameObjects.Count > 0)
{
GameObject go = gameObjects[gameObjects.Count - 1];
gameObjects.RemoveAt(gameObjects.Count - 1);
return go;
}
else
{
GameObject go = new GameObject();
go.AddComponent<MeshCollider>();
go.AddComponent<AutoDisabler>();
//go.AddComponent<MeshRenderer>();
//go.GetComponent<MeshRenderer>().material = new Material(Shader.Find("Standard"));
//go.AddComponent<MeshFilter>();
MeshCollider comp = go.AddComponent<MeshCollider>();
comp.sharedMaterial = ObjectPool.material;
GameObject.DontDestroyOnLoad(go);
return go;
}
}
public static void ReturnObject(GameObject go) //Returned shaders will have their values set, but this shouldn't matter as they won't be dispatched here
{
go.transform.parent = null;
gameObjects.Add(go);
}
}
}