I keep getting the following error on a script for this top down follow enemy:
NullReferenceException: Object reference not set to an instance of an object
Trapswan.MovePos (UnityEngine.Vector2 direction) (at Assets/Trapswan.cs:25)
Trapswan.FixedUpdate () (at Assets/Trapswan.cs:30)
I’ve looked at other similar issues online and they said the message means that something on the line doesn’t exist, but everything on that line does exist.
Yeah as @Dextozz said, don’t GetComponent every frame like that. Just do it once in Start or set it with an inspector reference. After you do that it should fix the issue.
You could additionally change MovePos in case you later mess up getting this reference in Start again though.
void MovePos(Vector2 direction)
{
if (rb == null)
{
Debug.Log("Trapswan.MovePos was called with rb null, setting rb");
rb = GetComponent<Rigidbody2D>();
}
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime))
//this is the error causer
}
I made this post a few days ago and have sense written completely new code to replace this one. I learned in the few days between now and this original post that putting GetCompnent() inside of Update is a BIG NO NO
Unity throws the following error:
NullReferenceException: Object reference not set to an instance of an object
Game_CNT+c__Iterator4.MoveNext () (at Assets/Scripts/Game_CNT.cs:499)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
I have 2 game objects in a scene:
Game_CNT
MP_Scripts
Game_CNT game object has “Game_CNT” script attached to it.
MP_Scripts game object has “MarketingScripts” script attached to it
When I call a method of the “MarketingScripts” from the “Game_CNT” it throws the error above.
Game_CNT:
public class Game_CNT : MonoBehaviour
{
GameObject MP_Scripts; // Get Reference of MP_Scripts
void ShowVideoAd()
{
MP_Scripts.GetComponent<MarketingScripts>().ShowUnityAdVideo(); // This one is in line 499
}
}
MarketingScripts:
public class MarketingScripts : MonoBehaviour
{
string gameID = "123456";
void Start()
{
Advertisement.Initialize(gameID, true); // Initializing Unity Ads
}
public void ShowUnityAdVideo() //To show Simple Skippable Video Ads
{
if (Advertisement.IsReady("video"))
Advertisement.Show("video");
else return;
}
}
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.