Skip to content

Instantly share code, notes, and snippets.

@Jakz
Created June 10, 2022 12:15
Show Gist options
  • Save Jakz/7c54f328ec973f3d8cab5d2df54a1227 to your computer and use it in GitHub Desktop.
Save Jakz/7c54f328ec973f3d8cab5d2df54a1227 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MobSpawner : MonoBehaviour
{
public class Trap
{
private static int ordinal = 0;
public Color Color { get; }
public int Ordinal { get; }
public Trap()
{
Color = Random.ColorHSV();
Ordinal = ordinal++;
}
}
List<Trap> traps;
List<Trap> inventory;
public class GridData : MonoBehaviour
{
public Trap Trap { get; set; }
}
const int SLOTS = 5;
// Start is called before the first frame update
void Start()
{
traps = new List<Trap>();
inventory = new List<Trap>();
/* populate random traps */
for (int i = 0; i < 16; ++i)
traps.Add(new Trap());
/* generate grid */
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
GameObject element = GameObject.CreatePrimitive(PrimitiveType.Quad);
element.transform.position = new Vector3(-2.0f + i * 0.6f, -2.0f + j * 0.6f, 0.0f);
element.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
element.GetComponent<Renderer>().material.color = traps[j + i * 4].Color;
element.AddComponent(typeof(GridData));
element.GetComponent<GridData>().Trap = traps[j + i * 4];
}
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit raycastHit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out raycastHit, 100f))
{
if (raycastHit.transform != null)
{
GameObject element = raycastHit.transform.gameObject;
Trap trap = element.GetComponent<MobSpawner.GridData>().Trap;
if (trap != null)
{
if (inventory.Count < SLOTS && !inventory.Contains(trap))
{
Debug.Log("Adding: " + trap.Ordinal);
inventory.Add(trap);
element.transform.Rotate(new Vector3(0.0f, 0.0f, 45.0f));
}
else if (inventory.Contains(trap))
{
Debug.Log("Removing: " + trap.Ordinal);
inventory.Remove(trap);
element.transform.Rotate(new Vector3(0.0f, 0.0f, -45.0f));
}
Debug.Log("Inventory size: " + inventory.Count);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment