Hey all, I’m having trouble with something that feels like it should be really simple, but I can’t for the life of me track down what’s wrong.
I have two scripts that need to talk to each other. One controls a couple of timers, mouse functionality, and the general management of the game; the other controls the movement of a beam when the mouse is clicked and dragged. I have a “NRE: Object reference not set to an instance of an object” issue on line 35 of Laser.cs, which I feel like is coming from something I didn’t do in LaserMove.cs.
I know the NRE issue is one that pops up a lot on here, and I spent a couple of days crawling through answers here and on everyone’s favorite search engine, but nothing seems to help. Would anyone be able to help me out?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Laser : MonoBehaviour {
public GameObject laserBeam;
public float beamTime = 2.0f;
public float laserCoolDownTime = 10.0f;
private bool laserAvailable = true;
public static Vector3 mousePos;
public static List<Vector3> mousePosList;
void Update ()
{
LaserRecord();
}
//record the mouse position every frame while LMB is down
void LaserRecord()
{
if (Input.GetMouseButton(0))
{
if (laserAvailable)
{
beamTime -= Time.deltaTime;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
mousePosList.Add(hit.point);
}
if (beamTime <= 0)
{
beamTime = 0;
laserAvailable = false;
}
}
}
//run a cooldown timer & beam movement after the mouse button is released and the laser is flagged unavailable
if (!Input.GetMouseButton(0) && !laserAvailable)
{
LaserCoolDown();
laserBeam.GetComponent<LaserMove>().BeamMovement();
}
}
void LaserCoolDown()
{
laserCoolDownTime -= Time.deltaTime;
if (laserCoolDownTime <= 0)
{
laserCoolDownTime = 10.0f;
beamTime = 2.0f;
laserAvailable = true;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LaserMove : MonoBehaviour {
private Vector3 targetPos;
public int moveSpeed = 3;
private Vector3 startPos = Laser.mousePos;
private List<Vector3> coordsArray = Laser.mousePosList;
public GameObject gameObject;
public void BeamMovement()
{
for (int i = 0; i > coordsArray.Count; i++)
{
startPos = coordsArray[i];
targetPos = coordsArray[i + 1];
float step = moveSpeed*Time.deltaTime;
gameObject.transform.position = Vector3.MoveTowards(startPos, targetPos, step);
}
}
}
Feedback on code is also appreciated. I’m not terribly experienced in programming.