Why am I getting NullReferenceException: Object reference not set to an instance of an object WorldInteraction.GetInteraction () Error?
Error seems to be at Ray object declaration or upon calling GetInteraction() method. Well I think so.
// Use this for initialization
void Start()
{
playerAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
GetInteraction();
}
void GetInteraction()
{
Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit interactionInfo;
if (Physics.Raycast(interactionRay, out interactionInfo, 100))
{
GameObject interactionObject = interactionInfo.collider.gameObject;
if (interactionObject.tag == "Interactable Object")
{
Debug.Log(interactionInfo.collider.gameObject.name);
}
else
{
playerAgent.destination = interactionInfo.point;
}
}
}
I've set the canvas as an UI and EventSystem was created
I am following this guy: https://www.youtube.com/watch?v=36ruPSD7FJk&t=35s
Answer by AndreM1 · Apr 04, 2017 at 02:21 PM
Instead, you can acess the transform of the object you hit. Maybe the object you hit doesn't even have a collider, get the transform(wich is sure to have), and if works, do GetComponent; at least that code work for me...
RaycastHit hit;
Ray ray = mainCamera.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)); // Also that part changes a bit.
if (Physics.Raycast(ray, out hit, 100)) {
Transform tr = hit.transform; //Game object transform.
Destroy(tr.gameObject); // Destroy the gameobject that was hit.
}
Hope that time works.
Thank you for your answer. After the night I returned back to my project and I realized that main camera wasn't tagged as main camera.
Your answer
Follow this Question
Related Questions
Making the player follow a path 0 Answers
[Unity, beginner. Help me.]Fire five parabolic lines in the desired random direction. 1 Answer
Wall Jump with Jump Delay 0 Answers
What Specs will fit our requirements (GTX/QUADRO, CPU, Memory)? at specific resolution 0 Answers
How can I Wall Jump with a Delay 1 Answer