Hello,
I am working on a small RTS game and just got started up a day ago. I am using a course for the initial setup and am having issues with getting the GameObjects (units) to be selected when i left click on them. I believe the course is a couple years old and there is some outdated feature/function which is causing the issue. I have looked through the code and rewatched the videos many times and I don’t see a programming issue which leads me to think it may be a Unity Editor problem.
I am getting the null reference exception error when i click on the unit or just click at all, instead of activating the highlighted ring that shows it is selected. In the course the layermask hasn’t come up just yet, but some of the forums and google answers I looked at used them. I tried incorporating those as best as I could but still got the error.
Here is my code, any suggestions or help is much appreciated.
`public class MouseManager : MonoBehaviour {
private List<Interactive> Selections = new List<Interactive>(); //A list of all the selections we have
// Update is called once per frame
void Update () {
//We put this code here so the selection is only performed exactly when we want it to, not every frame
//if we are not clicking the left mouse button, do nothing
if (!Input.GetMouseButtonDown(0))
return;
//if the user is clicking on a UI element, make sure it doesnt click on any 3D objects behind the UI
var es = UnityEngine.EventSystems.EventSystem.current; //create an event system
//since the event system may or may not exist, we need to check if it is null
if (es != null && es.IsPointerOverGameObject()) //returns true if over a 2D UI element
return;
//remove any selections we already have. So, check to see if we already have one
if (Selections.Count > 0) {
//if there is more than 0 items, then...
//if not holding down left or right shift keys
if(!Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.RightShift))
{
//if there is a selection and NOT holding shift keys...
foreach(var sel in Selections)
{
//if unit is destroyed or no longer there, need to make sure it is no longer selected. An exception error will occur elsewise.
if (sel != null) sel.Deselect();
}
Selections.Clear(); //clears the list
}
}
//find out if we have hit anything or not
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit; //set up raycast, called hit
if (!Physics.Raycast(ray, out hit))
return; //if it doesnt hit anything...exit
//if the ray does hit something, check to see if what was clicked was interactive
var interact = hit.transform.GetComponent<Interactive>();
if (interact == null)
return;
//selects the item (or unit)
Selections.Add(interact);
interact.Select();
}
}’
Thank you for your time.