0

I am new to C# and am trying to make a basic game in Unity. I am trying to add bullet gameObject to an array. I have researched how to add elements to an array in C# and have found the Add method. However, when I try to use this MonoDevelop doesn't highlight the method as if the method doesn't exist and I get an error. Here is is the error message:

Assets/Scripts/SpaceShipController.cs(126,25): error CS0118: SpaceShipController.gameManager' is afield' but a `type' was expected

Here is the line of code which trips the error:

gameManager.bullets[].Add(bulletObject);

Here is the rest of my code. The class called SpaceShipController trips the error when it tries to add bullet objects to an array in a GameManager objects with the script GameManager attached. Finally the BulletBehaviour class just makes the bullet move forward. The code is labelled by class:

SpaceShipController:

using UnityEngine;
using System.Collections;

public class SpaceShipController : MonoBehaviour {

    public GameObject bulletObject;

    public GameManager gameManager;

    //private GameObject[] bullets;

    public float shipSpeed;
    public float bulletSpeed = 1;

    private Vector3 spaceShip;

    private Quaternion spaceShipRotation;

    private Vector3 bulletPosition;

    private int coolDown = 10;

    private bool moveRight = false;
    private bool moveLeft = false;
    private bool fire = false;

    // Use this for initialization
    void Start () {

        spaceShip = transform.position;

        spaceShipRotation = transform.rotation;

        bulletObject.transform.position = bulletPosition;
    }

    // Update is called once per frame
    void Update () {

        coolDown--;

        inputHandler();

        this.transform.position = spaceShip;
    }

    void inputHandler() {

        if (Input.GetKeyDown(KeyCode.RightArrow)) {

            moveRight = true;

        }

        if (Input.GetKeyDown(KeyCode.LeftArrow)) {

            moveLeft = true;

        }

        if (Input.GetKeyUp(KeyCode.RightArrow)) {

            moveRight = false;

        }

        if (Input.GetKeyUp(KeyCode.LeftArrow)) {

            moveLeft = false;

        }

        if (Input.GetKeyDown(KeyCode.Space)) {

            fire = true;
        }

        if (Input.GetKeyUp(KeyCode.Space)) {

            fire = false;
        }

        if (moveRight == true) {

            spaceShip.x += shipSpeed;

        }

        if (moveLeft == true) {

            spaceShip.x -= shipSpeed;

        }


        if (coolDown <= 0) {

            if (fire == true) {

                Fire ();

                coolDown = 10;
            }

        }
    }

    void Fire () {

        for (var i = 0; i < 2; i++) {

            if (i == 0) {

                spaceShip = new Vector3 (transform.position.x + 0.9f, transform.position.y + 0.9f, transform.position.z);
            }

            else if (i == 1) {

                spaceShip = new Vector3 (transform.position.x - 0.9f, transform.position.y + 0.9f, transform.position.z);
            }

            Instantiate(bulletObject, spaceShip, spaceShipRotation);

            bulletObject.AddComponent<BulletBehaviour>();

            gameManager.bullets[].Add(bulletObject);

            spaceShip = this.transform.position;
        }
    }
}

GameManager:

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public GameObject[] bullets;

    public Camera cam;

    private Vector2 cameraBounds;

    // Use this for initialization
    void Start () {


        cameraBounds = new Vector2 (cam.orthographicSize * Screen.width/Screen.height, cam.orthographicSize);
    }

    // Update is called once per frame
    void Update () {

        /*for (int i = 0; i < bullets.Length; i++) {

            if (bullets[i].transform.position.y >= cameraBounds.y) {

                Destroy(bullets[i]);

            }
        }*/
    }
}

BulletBehaviour:

using UnityEngine;
using System.Collections;

public class BulletBehaviour : MonoBehaviour {

    public SpaceShipController ship;

    private Vector3 shipPosition;

    // Use this for initialization
    void Start () {

        shipPosition = transform.position;
    }

    // Update is called once per frame
    void Update () {

        shipPosition.y += 1;

        transform.position = shipPosition;
    }
}

As always any help would be greatly appreciated. Thanks in advance for any help you can provide.

4
  • When accessing the bullets variable, there is no need to have the [] brackets. You can say gameManager.bullets.Add(bulletObject); Commented Jul 12, 2014 at 16:42
  • @Simon That's right, the [] not needed to call methods on an array. But the bigger issue is, arrays have no Add method. Commented Jul 12, 2014 at 16:54
  • 1
    Also, for future reference, please provide the shortest code possible to recreate the issue, instead of a wall of text. The question is about how to add items to an array - you don't need to tell us about unity, and all those classes. See the Help Centre: How to create a Minimal, Complete, and Verifiable example Commented Jul 12, 2014 at 16:56
  • Alright thanks, I'll try to keep that in mind next time. Commented Jul 12, 2014 at 17:00

1 Answer 1

3

Arrays are fixed-size. This means that, once they have been initialized with a certain length (e.g., bullets = new GameObject[10]), its length can no longer change.

In order to "add" an item to a array, you have to specify in which position you'd like the item to be. By default, arrays' indexing is 0-based. For example, to insert an element in the first position:

bullets[0] = myItem;

If you don't know how many items you'll have beforehand, and want to add/remove items at will, you should use a resizable collection, such as List<T>.

public List<GameObject> Bullets {get; set;}

You can use it like so:

//initialize with 0 items
Bullets = new List<GameObject>();

//add a new item at the end of the list
Bullets.Add(item);

Read also:

Sign up to request clarification or add additional context in comments.

3 Comments

Was about to post pretty much the same answer, but you beat me to it.. +1 :)
Thanks for the help, your suggestion worked well. How would you go about cycling through a List?
@user3150583 You can cycle through a list's items using a foreach construct. If you scroll to the bottom of the documentation page for List<T> (linked on my answer), you'll see a few useful examples on how to use a list. The MSDN documentation is a great place to start learning C#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.