This code gives me this error “NullReferenceException: Object reference not set to an instance of an object”
Please Help me
public var spidy : GameObject;
public var aim : GameObject;
private var spidypos = Vector2(spidy.transform.position.x,spidy.transform.position.y);
private var aimdir = Vector2(aim.transform.position.x,aim.transform.position.y);
function Start () {
}
function Update ()
{
if (Input.GetMouseButtonDown(0))
{
var hit: RaycastHit2D = Physics2D.Raycast(spidypos,aimdir,10);
if (hit.collider != null)
{
Debug.Log("Hit");
}
else
{
Debug.Log("Didn't hit");
}
}
}
Without knowing at which line the error occurs it’s hard to tell where your problem is, but i would guess that you forgot to assign the gameobjects for “spidy” and “aim” in the editor.
Don’t run code outside functions; spidypos should be only declared outside functions, and the value can be assigned in Start. However you don’t actually need those variables, since Vector3 implicitly converts to Vector2. Also it’s unlikely you’d want to do that anyway, since you’d be stuck with the values that were assigned in Start and I doubt that’s what you want.
var hit: RaycastHit2D = Physics2D.Raycast(spidy.transform.position, aim.transform.position, 10);
Note that this wouldn’t actually work since Raycast uses a position and a direction. Either use a direction instead of aim.transform.position, or else use Linecast.