Using Rect[] to create multiple rectangles results in error
Rect[] rectangles;
// Use this for initialization
void Start () {
ListPoints();
}
void ListPoints() {
for (int i = 0; i < points.Length; i++) {
print (points[i].transform.position);
rectangles[i] = new Rect(Points[i].transform.position.x, Points[i].transform.position.y, xBuffer, yBuffer);
}
}
Using the code above, I get the error "Object reference not set to an instance of an object". It's worth noting, I can execute the code if I don't use an Array for rectangles, but then it will only create 1 rectangle. My goal is to create a rectangle around each point (as shown in the for loop).
Answer by MakeCodeNow · Oct 04, 2015 at 03:24 AM
You need to allocate the rectangles array itself. Something like...
void ListPoints() {
rectangles = new Rect[points.Length];
for (int i = 0; i < points.Length; i++) {
print (points[i].transform.position);
rectangles[i] = new Rect(Points[i].transform.position.x, Points[i].transform.position.y, xBuffer, yBuffer);
}
}
Although I found another way to do what I was trying to do (I simply added colliders to the game objects to find the touch points, rather than create rectangles and seeing if those are being touched).
I did go back and test the code and it works, well done. I would have never thought to create the Rect[points.length] part before using the array to make the rectangles. Learn something new every day :D
Your answer
![](https://koobas.hobune.stream/wayback/20220612035848im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity Inspector public large array - Lag and errors - Optimized GUI Block text buffer too large 0 Answers
NullReferenceException with serialized array 0 Answers
Creating an array of Color32 arrays 1 Answer
Get child button of and object in herarchy order 0 Answers
Multiple script instances in a scene but need to access certain ones 0 Answers