- Home /
Any idea why this is spitting out null reference exceptions?
NullReferenceException: Object reference not set to an instance of an object LookAtTarget.Fire () (at Assets/Scripts/LookAtTarget.cs:26)
using System;
using UnityEngine;
public class LookAtTarget : MonoBehaviour
{
public Rigidbody2D projectile;
public float speed = 1000;
public Transform target;
void Start()
{
InvokeRepeating("Fire", 3, 0.5f);
}
void Update()
{
if(target != null)
{
transform.LookAt(target);
}
}
void Fire()
{
Rigidbody2D instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation)as Rigidbody2D;
instantiatedProjectile.velocity = new Vector2(instantiatedProjectile.velocity.x,3);
}
}
@PvTGreg, is projectile assigned in the inspector? If not, it will be null. Check during playmode
Hi it is assigned it is firing them but not adding the velocity
Could you try to use "GameObject instantiatedProjectile=... as GameObject" ins$$anonymous$$d of "Rigidbody2D instantiatedProjectile =... as Rigidbody2D"?
Answer by Landern · Aug 25, 2014 at 02:37 PM
Add some debugging code, is it possible you're attaching somethign that isn't a rigidbody2d? Try an transform or gameobject instead.
Use this to see what the output is in the console:
void Fire()
{
if (projectile == null)
Debug.Log("Projectile is null");
else
Debug.Log("Projectile is NOT null");
if (transform == null)
Debug.Log("Transform is null");
else
Debug.Log("Transform is NOT null");
Rigidbody2D instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation)as Rigidbody2D;
if (instantiatedProjectile == null)
Debug.Log("instantiatedProjectile is null");
else
Debug.Log("instantiatedProjectile is NOT null");
instantiatedProjectile.velocity = new Vector2(instantiatedProjectile.velocity.x,3);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613161509im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to import the object from server to unity 2 Answers
Material doesn't have a color property '_Color' 4 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer