- Home /
Problems adding GameObjects to a GameObject array (C#)
Hello!
I'm declaring a GameObject array and then trying to add GameObjects to it.
My declaration looks like this:
public GameObject[] OrbitingSatellites = new GameObject[7];
And my code to add objects just isn't working. I feel like this might be close:
OrbitingSatellites[0] = orbital1;
where "orbital1" is the name of the GameObject I want in the array at position 0.
The errors it throws are
CS0120: 'Orbit.OrbitingSatellites': An object reference is required for the nonstatic field, method or property
CS0021: Cannot apply indexing with [] to an expression of type 'object'
Please help me find a solution, thank you.
EDIT: Declaration of orbital1 looks like this:
public GameObject orbital1;
I'm using this as a container for an instanced primitive sphere. In the inspector it checks out as a game object, and it is indeed a sphere that I'm manipulating.
@Jack, can you add the code that creates/declares orbital1? Are you sure it's of type GameObject, and not Object - and not null? :) And also not Transform - I still get those mixed up.
@Jack, on second thought, that would generate a type-conversion error. It sounds like there is something wrong with the array declaration, but I cut/paste it with no problem. Can you show more of the class code where OrbitingSatellites is declared?
@ Cyclops Yeah, cutting and pasting it straight has given me some insight into how it's supposed to work. The problem then isn't in how I'm handling the array, but somewhere else in the code, so I can close this question thanks to your help. $$anonymous$$uch appreciated!
Answer by Cyclops · Jul 07, 2010 at 04:30 PM
Here is a sample of the code I used, after cutting/pasting your lines into a script, which worked with no problem:
public class s_foo : MonoBehaviour { public GameObject[] OrbitingSatellites = new GameObject[7]; public GameObject orbital1; // drag-dropped "small explosion" in Editor.
void Start() {
OrbitingSatellites[0] = orbital1;
Debug.Log("os = " + OrbitingSatellites[0].name); // prints "small explosion"
}
}
What differences, if any, are in your code structure?
Answer by the Jack · Jul 07, 2010 at 04:34 PM
This is a correct method for adding game objects to a gameobject array, my problems lie elsewhere.
Your answer
