Last active
July 16, 2019 22:24
-
-
Save nekomimi-daimao/1b4c87b180a5b33e7b4e47514da213a3 to your computer and use it in GitHub Desktop.
Unity, Create Primitive Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
namespace NekomimiDaimao | |
{ | |
public class PrimitiveCreator | |
{ | |
private const float DefaultScale = 0.2f; | |
private readonly PrimitiveType _type; | |
private readonly Vector3 _scale; | |
private readonly Color _color; | |
private readonly List<GameObject> _createObjects; | |
#region Constructor | |
private PrimitiveCreator(PrimitiveType type, float scale, Color color) | |
{ | |
_type = type; | |
_scale = new Vector3(scale, scale, scale); | |
_color = color; | |
_createObjects = new List<GameObject>(); | |
} | |
public static PrimitiveCreator Initialize(PrimitiveType type, float scale = DefaultScale, Color color = default) | |
{ | |
return new PrimitiveCreator(type, scale, color); | |
} | |
#endregion | |
public GameObject Create(Vector3 position, Transform parent = null, Color? color = null) | |
{ | |
var obj = GameObject.CreatePrimitive(_type); | |
var ts = obj.transform; | |
if (parent != null) | |
{ | |
ts.SetParent(parent); | |
} | |
ts.localScale = _scale; | |
ts.position = position; | |
obj.GetComponent<Renderer>().material.color = color ?? _color; | |
_createObjects.Add(obj); | |
return obj; | |
} | |
public GameObject Create(Vector3 position, Color color) | |
{ | |
return Create(position, null, color); | |
} | |
public void Shrink() | |
{ | |
_createObjects.RemoveAll(o => o == null); | |
} | |
public void Clear() | |
{ | |
foreach (var gameObject in _createObjects) | |
{ | |
if (gameObject != null) | |
{ | |
GameObject.Destroy(gameObject); | |
} | |
} | |
_createObjects.Clear(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment