- Home /
 
               Question by 
               Vardius · Feb 18, 2013 at 03:00 PM · 
                c#gameobjectprimitive  
              
 
              C3 Creating GameObject in script why give me an error ?
i started new project and created a c# script attached to Main Camera
 using UnityEngine;
 using System.Collections;
 
 public class Main : MonoBehaviour
 {
     private GameObject[][] sphere;
 
     void Awake()
     {
         for (int i = 0; i < 13; i++)
             for (int j = 0; j < 11; j++)
             {
                 sphere[i][j] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                 sphere[i][j].transform.position = new Vector3(2 * i, 2 * j, 0);
                 sphere[i][j].transform.localScale = new Vector3(1, 1, 1);
                 sphere[i][j].renderer.material.color = Color.red;
             }
     }
 
     private void Start()
     {
     }
 
     private void Update()
     {
     }
 }
and when i tring if i can see spheres i got errors:
NullReferenceException: Object reference not set to an instance of an object Main.Awake () (at Assets/Main.cs:13)
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by robertbu · Feb 18, 2013 at 03:03 PM
You are declaring a jagged array (which I don't think is what you want). Plus you are not allocating space for the array. Try this:
 public class NewBehaviourScript : MonoBehaviour
 {
     private GameObject[,] sphere = new GameObject[13,11];
  
     void Awake()
     {
         for (int i = 0; i < 13; i++)
             for (int j = 0; j < 11; j++)
             {
                 sphere[i,j] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                 sphere[i,j].transform.position = new Vector3(2 * i, 2 * j, 0);
                 sphere[i,j].transform.localScale = new Vector3(1, 1, 1);
                 sphere[i,j].renderer.material.color = Color.red;
             }
     }
 
 }
Your answer
 
 
             Follow this Question
Related Questions
C# Rotate GameObjects Regardless of List Size 2 Answers
How to create an 3d game object in 300 X 250 size? 1 Answer
C# GameObject Reverses Z Rotation 0 Answers
Distribute terrain in zones 3 Answers
C# Find Which Axes Gameobject is on 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                