Object is continuously spawning prefabs - c#

I am using the Unity Engine to make a 2D game... to give you an idea of what it looks like, there is a generic space background, 4 rocks bouncing around the screen, and a tie fighter. My goal was to make the tie fighter explode (Which I did succeed in doing), destroy itself, and have a prefab take its place. I am new to c#, so I don't know much of the API. I tried using the second script to destroy the tie fighter, then instantiate a prefab... Now, whenever I run the game, it spawns enough clones to the point where Unity crashes and I do not know how to fix it. I tried googling stuff and doing a manual fix (hence the bools), but nothing seems to be working. Any help would be greatly appreciated. Also, please don't just comment; write it as an answer so that I can mark it correct if it works. Here are the scripts (I am assuming the error is in the second one, but I included both for reference):
First Script:
using UnityEngine;
using System.Collections;
public class tfScript : MonoBehaviour
{
Vector3 tfPos;
Vector3 worldPos;
float mousePosInBlocksx;
float mousePosInBlocksy;
int lives;
public Sprite tieFight; // Drag your first sprite here
public Sprite kaboom; // Drag your second sprite here
private SpriteRenderer spriteRenderer;
float makeThingsGoBoom;
// Use this for initialization
public void Start ()
{
tfPos = new Vector3 (3f, 3f, -4f);
lives = 20;
spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
{
spriteRenderer.sprite = tieFight; // set the sprite to sprite1
}
}
// Update is called once per frame
public void Update ()
{
GameObject controller = GameObject.Find ("controller");
gameController gameCon = controller.GetComponent<gameController> ();
mousePosInBlocksx = ((Input.mousePosition.x / Screen.width) * 16);
mousePosInBlocksy = ((Input.mousePosition.y / Screen.width) * 12)+2;
tfPos.x = Mathf.Clamp (mousePosInBlocksx, .5f, 15.5f);
tfPos.y = Mathf.Clamp (mousePosInBlocksy, .5f, 11.5f);
this.transform.position = tfPos;
if (makeThingsGoBoom == 0)
{
gameCon.Update();
}
}
public void ChangeTheDarnSprite ()
{
if (spriteRenderer.sprite == tieFight) { // if the spriteRenderer sprite = sprite1 then change to sprite2
spriteRenderer.sprite = kaboom;
}
else
{
spriteRenderer.sprite = tieFight;
}
}
public void OnCollisionEnter2D (Collision2D collider)
{
if (collider.gameObject.name.Contains("spacerock") )
{
lives--;
print (getLives ());
}
if (collider.gameObject.name.Contains("spacerock")) // If the space bar is pushed down
{
spriteRenderer.sprite = kaboom;
makeThingsGoBoom = 0;
}
}
public void increaseLives()
{
lives++;
}
public double getLives()
{
return lives;
}
}
Second Script:
using UnityEngine;
using System.Collections;
public class gameController : MonoBehaviour
{
public GameObject tf;
public GameObject tfpf;
public bool iBlowedUp = false;
public void Start()
{
}
public void Update ()
{
boom ();
}
public void boom()
{
iBlowedUp = true;
if (iBlowedUp = true)
{
StartCoroutine (waitForIt ());
Destroy (tf);
tfpf = Instantiate (Resources.Load ("Prefabs/tfpf")) as GameObject;
iBlowedUp = false;
}
}
public IEnumerator waitForIt()
{
print ("Bob lives #2!");
yield return new WaitForSeconds (1);
print ("John is a turtle #2!");
}
}

You are calling following method in a Update function which is executed constantly.
public void boom()
{
iBlowedUp = true;
if (iBlowedUp = true)
{
StartCoroutine (waitForIt ());
Destroy (tf);
tfpf = Instantiate (Resources.Load ("Prefabs/tfpf")) as GameObject;
iBlowedUp = false;
}
}
An if iBlowedUp = true; if (iBlowedUp = true){ doesn't make sense, because the statement is true always.
It should be similar to:
public void boom()
{
if (iBlowedUp == true)
{
iBlowedUp = false;
StartCoroutine (waitForIt ());
Destroy (tf);
tfpf = Instantiate (Resources.Load ("Prefabs/tfpf")) as GameObject;
}
}
Probably you want to set iBlowedUp to true somewhere else. As I consider in a tfScript.Update() method, instead of calling Update method.
if (makeThingsGoBoom == 0)
{
gameCon.iBlowedUp = true;
//gameCon.Update();
}

if (iBlowedUp = true)
{
iBlowedUp = false;
StartCoroutine (waitForIt ());
Destroy (tf);
tfpf = Instantiate (Resources.Load ("Prefabs/tfpf")) as GameObject;
}
before instantiate make isBlowedUp false, I cant say ı understood well this "Unity crashes". there is some complexity in your code. I hope you fix them as well

Related

How to play the right sound when selected on a object in unity/c#

I tried by making a script to when I tap on a object on my scene to make sound. So, I have audio source and my script implemented on the object. However, with my script below it only deploys the first audio that i have which is (cup). What I want to change in my code or make it better is dont let audio run until I click on the object. and any way to do where I click on a object the audio triggers? please advise. thanks for the help.
Update: Right now, if I select everywhere the sound triggers and whenever I click on other object it gives the one audio of all of my object, that is not what I wanted.
here is my code:
public class TextToSpeech : MonoBehaviour
{
[SerializeField] AudioClip _audioClip;
[SerializeField] [Range(0.0f, 1.0f)] float _volume = 1;
AudioSource _audioSource;
public AudioClip SoundToPlay;
public float Volume;
public bool alreadyPlayed = false;
public bool playOnAwake = false;
private Touch touch;
private Vector2 beginTouchPosition, endTouchPosition;
private bool isPlaying;
void Start()
{
_audioSource = GetComponent<AudioSource>();
_audioSource.clip = _audioClip;
_audioSource.volume = _volume;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
_audioSource.enabled = true;
if (!_audioSource.isPlaying) {
_audioSource.clip = SoundToPlay;
_audioSource.Play ();
}
else
{
_audioSource.enabled = false;
}
}
}
}
So, After realizing you problems I changed this answer.
At first your code must be attached only one gameobject, for example camera, like this
also I named my script StackOverflow, you can name it whatever you want.
And BoxCollider must be attached to your plastic bottle or cup, like this
you can set it to trigger or nontrigger(depended on your necessity) and set its size to fit the real size of your objects in the scene.
and at last this is the Script which I named StackOverFlow, and SpeechToText in your case
public class StackOverFlow : MonoBehaviour {
[SerializeField] AudioClip _audioClip;
[SerializeField] [Range(0.0f, 1.0f)] float _volume = 1;
AudioSource _audioSource;
bool isPlaying;
void Start() {
_audioSource = GetComponent<AudioSource>();
_audioSource.clip = _audioClip;
_audioSource.volume = _volume;
}
void Update() {
if (Input.touchCount > 0) {
Touch touch = Input.touches[0];
if (touch.phase == TouchPhase.Began) {
Ray touchRay = Camera.main.ScreenPointToRay(touch.position);
Physics.Raycast(touchRay, out RaycastHit hit, Mathf.Infinity);
if (hit.collider != null) {
if (hit.collider.name.Contains("Cup") || hit.collider.name.Contains("Bottle")) {
PlaySound();
}
else {
Debug.Log($"otherobject {hit.collider.name}");
}
}
}
}
}
private void PlaySound() {
if (!isPlaying) {
_audioSource.Play();
isPlaying = true;
StartCoroutine(CheckIfPlaying());
}
}
private IEnumerator CheckIfPlaying() {
yield return new WaitForSeconds(_audioClip.length);
isPlaying = false;
}
}
ask me in comments if something is unclear
So you seem to be misunderstanding the use of OnTriggerEnter, you would be better raycasting from the touch position and playing based on that
void Update()
{
Camera mainCam = Camera.main;
for (int i = 0; i < Input.touchCount; ++i)
{
Vector3 touchPos = mainCam.ScreenToWorldPoint(Input.GetTouch(i).position);
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.forward);
if(hit.gameObject == this.gameObject){
// play sound
}
}
}

Unity3D Shooter - How to switch to next level after all enemies get destroyed?

I am a newbie to Unity and I am trying to build a little shooter 2d game in C#. I am now stuck and confess that I am a little lost not knowing what the best approach is, but the problem is that my hero shoots at the enemies and they die but how do I get to the next level after the enemies are all dead? If I make a dead counter, what script do I put in? In the enemy script? Or do I make a new script but associate it with what? I also need the game to end if the hero fires his six bullets (already have a counter that makes the hero not shoot anymore after six shoots) and there are still enemies left ...
Does anyone give me some tips? Thanks!
Enemy script:
using System.Collections.Generic;
using UnityEngine;
public class BadguyScript : MonoBehaviour
{
public int maxHealth;
public int curHealth;
private Animator myAnimator;
private bool isDead;
[SerializeField]
private float DespawnTime = 2.5f;
[SerializeField]
private string DeathAnimHash = "isDead";
void Start()
{
myAnimator = GetComponent<Animator>();
myAnimator.enabled =true;
myAnimator.SetBool (DeathAnimHash ,isDead);
maxHealth = 1;
curHealth = maxHealth;
}
void Update()
{
if (curHealth < 1)
{
isDead = true;
myAnimator.SetBool (DeathAnimHash ,isDead);
Destroy(gameObject,DespawnTime);
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (isDead)
return;
if (col.tag == "bullet")
{
curHealth -= 1;
Destroy(col.gameObject);
}
}
}
Count Bullets Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameFlow : MonoBehaviour
{
public static float remainingShots = 6;
public Transform shot1;
public Transform shot2;
public Transform shot3;
public Transform shot4;
public Transform shot5;
public Transform shot6;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (remainingShots > 0)
{
shot1.GetComponent<Image> ().enabled = true;
}
else
{
shot1.GetComponent<Image> ().enabled = false;
}
if (remainingShots > 1)
{
shot2.GetComponent<Image> ().enabled = true;
}
else
{
shot2.GetComponent<Image> ().enabled = false;
}
if (remainingShots > 2)
{
shot3.GetComponent<Image> ().enabled = true;
}
else
{
shot3.GetComponent<Image> ().enabled = false;
}
if (remainingShots > 3)
{
shot4.GetComponent<Image> ().enabled = true;
}
else
{
shot4.GetComponent<Image> ().enabled = false;
}
if (remainingShots > 4)
{
shot5.GetComponent<Image> ().enabled = true;
}
else
{
shot5.GetComponent<Image> ().enabled = false;
}
if (remainingShots > 5)
{
shot6.GetComponent<Image> ().enabled = true;
}
else
{
shot6.GetComponent<Image> ().enabled = false;
}
if(Input.GetButtonDown("Fire1"))
{
remainingShots -= 1;
}
}
}
To switch to another scene after your conditions do the following:
1. Add the OtherScenes to your game by doing this:
File -> Build Settings -> Add Open Scenes
2. Do something like this in your code:
Enemy Script.cs
using UnityEngine.SceneManagement; // Contains scene management functions
public GameObject[] enemies;
void Update()
{
enemies = GameObject.FindGameObjectsWithTag("Enemy"); // Checks if enemies are available with tag "Enemy". Note that you should set this to your enemies in the inspector.
if (enemies.length == 0)
{
SceneManager.LoadScene("OtherSceneName"); // Load the scene with name "OtherSceneName"
}
}
Bullet Script.cs
using UnityEngine.SceneManagement;
void Update()
{
if (remainingShots == -1)
{
SceneManager.LoadScene("OtherSceneName");
}
}
use an empty gameobject and attach this line of code in update method .
if (enemies.length == 0)
{
SceneManager.LoadScene("OtherSceneName"); // Load the scene with name "OtherSceneName"
}
As you were using the enemy script and when all the enemies dies then there is no gameobject which hold the script.

After ending the scene need to start new scene

I'm doing an educational game for kids..
But I stopped at the end of the scene
I could not make a code to start the new scene..
in the First Script
when play game the scenes does not stop until the last scene.
YouWin.pictureInPlace++;
I searched a lot and did not find my question, so I consulted you. It was easier to do a button to go to the Next scene but I prefer to do it automaticly
I think this task can be accomplished by the boolean but its need to reference game object.. and the script on 2 images.
The First Script (Manager) has put on Four images At Canvas..
The second one (YouWin) I put on empty GameObject..
thanks for the help
The first script (Manger)
using UnityEngine;
using UnityEngine.EventSystems;
public class Manager : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
Vector2 pos1;
public GameObject pos2;
private bool canMove;
public GameObject winner;
void Start()
{
pos1 = transform.position;
canMove = true;
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log(eventData);
}
public void OnDrag(PointerEventData eventData)
{
if (canMove)
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, pos2.transform.position);
if (distance < 50)
{
transform.position = pos2.transform.position;
transform.localScale = pos2.transform.localScale;
canMove = false;
winner.GetComponent<YouWin>().pictureInPlace++;
}
else
{
transform.position = pos1;
}
}
}
The second script (YouWin)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YouWin : MonoBehaviour
{
public int NumberOfImages;
public int pictureInPlace;
public string sceneName;
void Update()
{
if (pictureInPlace == NumberOfImages)
{
StartCoroutine(LoadScene());
Debug.Log("You Win!");
}
}
IEnumerator LoadScene()
{
yield return new WaitForSeconds(1.5f);
SceneManager.LoadScene(sceneName);
}
}
It looks like you didn't reference YouWin in your Manager script. You should include it by adding it as a global variable public YouWin <variable_name>; or by referencing your empty GameObject and getting the YouWin component:
public GameObject emptyObject;
emptyObject.GetComponent<YouWin>().picturesInPlace++;
After all thanks for helping me but I was able to find the right solution
just make in the first Script (Manager) :
bool static Done;
void Start()
{
bool Done = false;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, pos2.transform.position);
if (distance < 50)
{
transform.position = pos2.transform.position;
transform.localScale = pos2.transform.localScale;
canMove = false;
bool Done = True;
}
}
and just call it from the second Script (YouWin)
public string sceneName;
void Update()
{
if(Youwin.Done)
{
StartCoroutine(LoadScene());
}
}
IEnumerator LoadScene()
{
yield return new WaitForSeconds(0.5f);
SceneManager.LoadScene(sceneName);
}
This IS The right solution ;

Unity: An object reference is required to access non-static member - Ray cast to GameObject

I'm making an RTS style game and i've got an error.
I'm trying to send the current selected unit (the object the script is on) to the Playmaker FSM of the object the raycast hit. I realised that you cannot access gameobjects and transforms inside of a static function so I tried to call another function to use the hit and fill the gameobject variable.
This is the error:
Assets/Scripts/Unit.cs(57,41): error CS0120: An object reference is required to access non-static member `Unit.SetOurObject(UnityEngine.RaycastHit)'
The main issue I think is here:
public static Vector3 GetDestination()
{
if (moveToDestination == Vector3.zero)
{
RaycastHit hit;
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(r, out hit))
{
while (!passables.Contains(hit.transform.gameObject.name))
{
if (!Physics.Raycast(hit.transform.position, r.direction, out hit)) //point + r.direction * 0.1f
break;
}
//gameObject.GetComponent<NavMeshAgent>().SetDestination(hit.point);
//if (hit.transform != null){
//print (hit);
if (resources.Contains(hit.transform.gameObject.name)){
SetOurObject(hit);
//SelectedUnit.Value = GameObject.name;
//ResourceHit.Fsm.Event("startHit");
} else {
moveToDestination = hit.point;
}
//}
}
}
return moveToDestination;
}
public void SetOurObject(RaycastHit hitRay)
{
ourObject = hitRay.transform.gameObject;
PlayMakerFSM ourFSM = ourObject.GetComponent<PlayMakerFSM>();
FsmGameObject SelectedUnit = ourFSM.FsmVariables.GetFsmGameObject("SelectedUnit");
SelectedUnit.Value = new GameObject();
ourFSM.Fsm.Event("ResourceHit");
}
And here is the whole script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using HutongGames.PlayMaker;
public class Unit : MonoBehaviour {
public PlayMakerFSM ResourceHit;
public GameObject ourObject;
public bool selected = false;
private Color SelectedCol = new Color(0.114f, 0.22f, 0.039f, 1.0f);
private Color UnselectedCol = new Color(0.357f, 0.604f, 0.184f, 1.0f);
private bool selectedByClick = false;
private Vector3 moveToDest = Vector3.zero;
private static Vector3 moveToDestination = Vector3.zero;
private static List<string> passables = new List<string>() { "Floor" };
private static List<string> resources = new List<string>() { "Res_Wood" };
// Update is called once per frame
private void CleanUp()
{
if (!Input.GetMouseButtonUp(1))
moveToDestination = Vector3.zero;
}
private NavMeshAgent agent;
void Start() {
agent = GetComponent<NavMeshAgent>();
}
public static Vector3 GetDestination()
{
if (moveToDestination == Vector3.zero)
{
RaycastHit hit;
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(r, out hit))
{
while (!passables.Contains(hit.transform.gameObject.name))
{
if (!Physics.Raycast(hit.transform.position, r.direction, out hit))
break;
}
if (resources.Contains(hit.transform.gameObject.name)){
SetOurObject(hit);
} else {
moveToDestination = hit.point;
}
}
}
return moveToDestination;
}
public void SetOurObject(RaycastHit hitRay)
{
ourObject = hitRay.transform.gameObject;
PlayMakerFSM ourFSM = ourObject.GetComponent<PlayMakerFSM>();
FsmGameObject SelectedUnit = ourFSM.FsmVariables.GetFsmGameObject("SelectedUnit");
SelectedUnit.Value = new GameObject();
ourFSM.Fsm.Event("ResourceHit");
}
void Update () {
CleanUp();
if (this.GetComponent<Renderer>().isVisible && Input.GetMouseButton(0))
{
if (!selectedByClick){
Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
camPos.y = CameraOperator.InvertMouseY (camPos.y);
selected = CameraOperator.selection.Contains(camPos);
}
if (selected)
this.GetComponent<Renderer> ().material.color = UnselectedCol;
else
this.GetComponent<Renderer> ().material.color = SelectedCol;
}
if (selected && Input.GetMouseButtonUp(1))
{
Vector3 destination = GetDestination();
if (destination != Vector3.zero)
{
gameObject.GetComponent<NavMeshAgent>().SetDestination(destination); //all you need if you have unity pro
//moveToDest = destination;
//moveToDest.y += floorOffset;
}
}
}
private void OnMouseDown()
{
selectedByClick = true;
selected = true;
}
private void OnMouseUp()
{
if (selectedByClick)
selected = true;
selectedByClick = false;
}
}
}
Thanks in advance! =)
Even though Christos is right about why it throws an exception (you're trying to access an instance method as if it was a static method), he's missing one detail.
In Unity3D you can't instantiate (easily) classes that implement MonoBehaviour. You create them by attaching a script component to existing gameobjects and then you can reference them in the code.
So to solve this, if you want to call that method, you have to first get a reference to the attached script component that's in the Scene and then you can do it.
Simple example, let's say the script component Unit is attached to the same GameObject, you reference it like this:
Unit unit = GetComponent<Unit>();
// now we can call instance fields/properties/methods on this specific instance!
From the error message you got, it is clear that the method
SetOurObject(UnityEngine.RaycastHit)
is not a static method of the class Unit.
Hence, you have first create an instance of this class and after this call this method.
// I don't know exactly the signature of the constructor class
// If it is parameterless or not etc.
// So you have to correct it correspondingly, If I am wrong.
var unit = new Unit();
Then you could call the method using this object.
unit.SetOurObject(UnityEngine.RaycastHit);

Adding Elements To An Array Using Array.Add

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.
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:
Arrays Tutorial
List<T> class
C# Collections

Categories

Resources