- Home /
Two Objects in the same position?
Hi there. I'm about creating a new RTS Game where you can place buildings and also some defenses on top of them. But unfortunately, you can place two objects in the same position which I don't want. All the prefabs have a rigid body ( Kinematic is true ) and a mesh collider (isTrigger is false). I set the layer for my prefabs to "ignore by raycast" so that my prefabs don't fly at me. Now what I want to achieve is to be able to place objects freely in the world and some objects like lights and guns on top of some buildings. Here is my building manager script.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildingManager : MonoBehaviour
{
[SerializeField]
private GameObject[] placeableObjectPrefabs;
[SerializeField]
private GameObject currentPlaceableObject;
private int currentPrefabIndex = -1;
void Update()
{
HandleNewObjectHotKey();
if (currentPlaceableObject != null)
{
MoveCurrentObjectToMouse();
ReleaseIfClicked();
}
}
private void ReleaseIfClicked()
{
if (Input.GetMouseButtonDown(1))
{
currentPlaceableObject = null;
}
}
private void MoveCurrentObjectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if(Physics.Raycast(ray,out hitInfo))
{
currentPlaceableObject.transform.position = hitInfo.point;
currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}
}
private void HandleNewObjectHotKey()
{
for(int i = 0; i < placeableObjectPrefabs.Length; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha0 + 1 + i))
{
if (PressedKeyOfCurrentPrefab(i))
{
Destroy(currentPlaceableObject);
currentPrefabIndex = -1;
}
else
{
if (currentPlaceableObject != null)
{
Destroy(currentPlaceableObject);
}
currentPlaceableObject = Instantiate(placeableObjectPrefabs[i]);
currentPrefabIndex = i;
}
break;
}
}
}
private bool PressedKeyOfCurrentPrefab(int i)
{
return currentPlaceableObject != null && currentPrefabIndex == i;
}
}
Thank you so much!!!
Comment