using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Renderer))]
public class ObjectPlacer : MonoBehaviour
{
private List<GameObject> _collidingObjects = new List<GameObject>();
private Material _material = null;
private Color _startingColor = Color.black;
public Color invalidPlacementColor = Color.red;
void Start()
{
_material = GetComponent<Renderer>().material;
_startingColor = _material.color;
}
void Update()
{
if (IsPositionValid())
_material.color = _startingColor;
else
_material.color = invalidPlacementColor;
}
void OnTriggerEnter(Collider other)
{
if (!_collidingObjects.Contains(other.gameObject))
{
_collidingObjects.Add(other.gameObject);
print("Colliding");
}
}
void OnTriggerExit(Collider other)
{
if (_collidingObjects.Contains(other.gameObject))
{
_collidingObjects.Remove(other.gameObject);
}
}
bool IsPositionValid()
{
return _collidingObjects.Count == 0;
}
}
Please note that for this sample code to work I made the colliding object a kinematic rigid body with a trigger collider. The OnTriggerEnter is only triggered if one of the two objects touching is a rigid body and the object the behaviour is on has a collider with "isTrigger" set to true.