Hey girls/guys,
I’m using Unity’s newest version together with the HDRP and I’m trying to have a default 3D Object in my scene, that generates a button when left-clicked.
This is supposed to be a town that has a building menu when you click on it with your left mouse button. I’m not a coder/programmer myself and just wanted to look at how well Unity would take scripts written by ChatGPT 3.5.
Many scripts seem not to be working at all, but from my sparce programming knowledge those programs seem utterly fine and logical to me as a beginner.
The console throws me the error, when left-clicking on it:
UnassignedReferenceException. The variable button Prefab of ObjectInteraction has not been assigned.
Can anyone whos looking at the code tell me what I did wrong?
That’s the code I’m using:
using UnityEngine;
using UnityEngine.UI; // Import Unity UI namespace
public class ObjectInteraction : MonoBehaviour
{
public Camera mainCamera;
public GameObject buttonPrefab; // Change this to a GameObject prefab containing a button component
public LayerMask layerMask;
private GameObject currentButton;
private bool buttonVisible = false;
void Start()
{
HideButton();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
Collider objectCollider = hit.collider;
if (objectCollider != null)
{
if (!buttonVisible)
{
ShowButton(hit.point, hit.normal);
buttonVisible = true;
}
else
{
HideButton();
buttonVisible = false;
}
}
}
}
}
void HideButton()
{
if (currentButton != null)
{
currentButton.SetActive(false); // Disable the button instead of destroying it
}
}
void ShowButton(Vector3 position, Vector3 normal)
{
if (currentButton == null)
{
currentButton = Instantiate(buttonPrefab, position + normal * 0.1f, Quaternion.LookRotation(-normal), transform);
// Make sure to adjust the position, rotation, and parent of the instantiated button as needed
}
else
{
currentButton.transform.position = position + normal * 0.1f;
currentButton.transform.rotation = Quaternion.LookRotation(-normal);
currentButton.SetActive(true); // Enable the button
}
}
}
As the Error Message says, you didn't assign the variable buttonPrefab. You can do that in the Unity Editor, as the Variable is marked as public.
– Meistermine