HI I’m new to programming and I’m trying to join a couple of scripts. the raycast part of the script seems to return an nullreferenceexception and I don’t find the solution. The code is :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TargettingSystem : MonoBehaviour {
public List <Transform> targets;
public Transform selectedUnit;
void Start()
{
targets = new List <Transform> ();
AddAllEnemies ();
selectedUnit = null;
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Tab))
{
targetEnemy ();
}
if (Input.GetMouseButtonDown(0))
{
SelectTarget ();
}
}
void SelectTarget()
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 10000))
{
if (hit.transform.tag == "Enemy")
{
selectedUnit = hit.transform.gameObject.transform;
}
}
}
public void AddAllEnemies()
{
GameObject[] go = GameObject.FindGameObjectsWithTag ("Enemy");
foreach (GameObject enemy in go)
AddTarget (enemy.transform);
}
public void AddTarget (Transform enemy)
{
targets.Add(enemy);
}
private void targetEnemy()
{
selectedUnit = targets [0];
}
}
Because the error takes place in line 29:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
It could be a ray issue, a camera issue or an input issue.
Ray ray (should be a ray) > ScreenPointToRay() (That’s a ray).
Camera.main > Should be a camera. Are you sure about this? Maybe try to assign the camera to a variable to see if there are any problems there. I saw something in this post:
Maybe you have a script called “Camera” that is messing things up?
Input.mousePosition, cant see anything wrong there. The combination of ScreenPointToRay(Input.mousePosition) is used a lot so I don’t see why there would be a problem there.
Try to mess around with the camera, maybe that’s where the problem is. Because when your “Camera.main” isn’t a real camera, you cant call a method like ScreenPointToRay on it, and it will return a error.