NullReferenceException being set off when it shouldn't be?
Hi!
Title says it all but for some reason my script ends up setting off "NullReferenceException: Object reference not set to an instance of an object" when it really shouldn't be.
I've checked to see that all the objects have Tranforms, which they do! I used Debug.Log() to make sure the math works out, which does. All the parts seem to be fine but when the code goes to put the Vector3 into the array, the exception is called.
public class SelectMove : MonoBehaviour {
private static Vector3[] worldposition;
private static GameObject[] worlds;
private void Start()
{
worlds = GameObject.FindGameObjectsWithTag("Worldddd");
for (int i = 0; i < 2; i++)
{
worldposition[i] = (transform.position - worlds[i].GetComponent<Transform>().position); //this sets off the Exception
}
}
}
Answer by Robxd0 · Jul 06, 2018 at 11:46 PM
Hello @MPHYS ,
first of all, the variable worldposition
is just defined, but as I see here, it's never initialized. You need to initialize it before you can use it. And also, you seem to check for an exact amount of objects in your for loop: (int i = 0; i < 2; i++)
and GameObject.FindGameObjectsWithTag("Worldddd");
may not return that many objects. For example it may return only two, so that way the third one (`worlds[2]`) may not exist and you will bump again into an error. Just try:
public class SelectMove : MonoBehaviour {
private static Vector3[] worldposition;
private static GameObject[] worlds;
private void Start()
{
worlds = GameObject.FindGameObjectsWithTag("Worldddd");
worldposition = worlds.Length;
for (int i = 0; i < worlds .length; i++)
{
worldposition[i] = (transform.position - worlds[i].transform.position);
}
}
I hope I could help, good luck!
Thank you!!! I totally forgot to intialize the second array. And thanks for pointing out the loop thing, I forgot to change it back int worlds.Length. Thanks again!!
Your answer
Follow this Question
Related Questions
Unhandled Exception: System.StackOverflowException when using Switch Statement? 1 Answer
Enoent error: diskusage.node not found when starting Unity Hub 0 Answers
the type initializer for "Hypixel.NET.Hypixel.Api" threw an exception 0 Answers
unity c# - IndexOutOfRangeException 1 Answer
File.Move won't work : IOException: Win32 IO returned ERROR_ALREADY_EXISTS. Path: 0 Answers