I am having a really hard time trying to create a piece of code that would add objects that I would select into an array. I was doing some research and it said that I would only be able to do the array.Add or array.Push in java. Which sucks because our project is in C#, is there any alternative that I could possible look into for this problem
Thanks,
Nolan Encarnacion
using UnityEngine;
using System.Collections;
public class SelectionManager : MonoBehaviour
{
public RaycastHit hit;
public Ray ray;
public GameObject[] selection;
// Use this for initialization
// Update is called once per frame
void Update ()
{
if ( Input.GetMouseButtonDown(0) )
{
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100))
{
addtoArray(hit.collider.gameObject);
Debug.Log(selection);
//Debug.Log(hit.collider.gameObject.name);
}
}
}
void addtoArray(gameObject obj)
{
selection.Add(obj);
}
}
No, you have to recreate the array with its new member. You may as well make it a generic method:
using System.Collections.Generic;
public static class Extensions {
public static T[] AddItemToArray <T> (this T[] original, T itemToAdd) {
T[] finalArray = new T[ original.Length + 1 ];
for(int i = 0; i < original.Length; i ++ ) {
finalArray _= original*;*_
_*}*_
_*finalArray[finalArray.Length - 1] = itemToAdd;*_
_*return finalArray;*_
_*}*_
_*}*_
_*```*_
_*<p>So as you can see, it isn't very easy to resize arrays.</p>*_
_*<p>Or, as Mike said right before I posted, you should probably just use a List. It will handle this for you.</p>*_