quhluh icon

Untitled

quhluh | 05/29/23 11:50:37 PM UTC | 0 ⭐ | 315 👁️ | Never ⏰ | []
C# |

1.06 KB

|

None

|

0 👍

/

0 👎

using UnityEngine;
 
public class ObjectPlacementAndDestruction : MonoBehaviour
{
    public GameObject objectPrefab;
 
    void Update()
    {
        // Place the object at the mouse position when the left mouse button is clicked
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
 
            if (Physics.Raycast(ray, out hit))
            {
                Vector3 spawnPosition = hit.point;
                Instantiate(objectPrefab, spawnPosition, Quaternion.identity);
            }
        }
 
        // Destroy the object at the mouse position when the right mouse button is clicked
        if (Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
 
            if (Physics.Raycast(ray, out hit))
            {
                GameObject objectToDestroy = hit.collider.gameObject;
                Destroy(objectToDestroy);
            }
        }
    }
}

Comments