- Home /
Object reference not set to an instance of an object with object set,
I am having an issue with getting my code to run properly because of the error "Object reference not set to an instance of an object." From what I have seen, this is due to there not being an object set, as the error suggest. However, I do have an object set, it just doesn't seem to recognize it. Here is my code:
public GameObject ChaserModel;
public Transform[] OriginPoint;
private GameObject[] Chasers;
void Start() {
for (int i = 0; i < OriginPoint.Length; i++) {
Chasers[i] = Instantiate(ChaserModel);
Chasers[i].transform.position = OriginPoint[i].transform.position;
}
Destroy(ChaserModel);
}
So, in this part of the code, I want to create an instance of ChaserModel and attach it to an array called Chasers, then, when created, I want it to be set to a position on the OriginPoint Array, then finally, it will destroy the original model. The problem is at the line Chasers[i] = Instantiate(ChaserModel);
It will create one clone of the object, then throw the NullRefrenceException error. It also won't move the Chasers model to the point it is supposed to move it to.
,
Answer by wachief · Nov 28, 2016 at 08:02 PM
Hello,
You are missing a very small but crucial line.
You Instantiate an object, and that works fine, but then you try to put it in an array. That array is never constructed and is there for null. The line you are missing is
Chasers= new GameObject[size];
Size is the size of the array you want to create. In your case it would be OriginPoint.Length so the line would look like this
Chasers= new GameObject[OriginPoint.Length];
With your code it will look like this:
public GameObject ChaserModel;
public Transform[] OriginPoint;
private GameObject[] Chasers;
void Start() {
Chasers= new GameObject[OriginPoint.Length];
for (int i = 0; i < OriginPoint.Length; i++) {
Chasers[i] = Instantiate(ChaserModel);
Chasers[i].transform.position = OriginPoint[i].transform.position;
}
Destroy(ChaserModel);
}
I hope this will help
You are right about setting a size for the array, but i still get the same error of @ebrown38 even with this code. It only works with me if i remove "private" from "GameObject[] Chasers;"
This script throws no errors for me. $$anonymous$$aybe you are doing something wrong in the editor. do you have all the point in OriginPoint array set? ( I would rename it to OriginPoints has its a Collection)
Your answer
![](https://koobas.hobune.stream/wayback/20220612101613im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiate object in for loop with array 2 Answers
Can't assign an instantiated class to an array? 1 Answer
adding "X" amount of objects to an array 2 Answers
Prefabs instantiated from an array are keeping their public int value 1 Answer
Material[] Object reference not set when instantiating 2 Answers