- Home /
Question by
SavageX370 · Nov 27, 2018 at 05:11 AM ·
scripting problemsizearray of gameobjectsupdate problem
New to unity/scripting: How can I update the size of my Gameobject Array so that it will not include missing prefabs/Gameobjects?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Addonclick : MonoBehaviour
{
public List<GameObject> prefabs;
public Transform[] spawnLocations;
public RaycastHit hit;
public Ray ray;
public float YAxisAngle;
void Start ()
{
}
private void Update ()
{
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100))
{
hit.rigidbody.gameObject.tag = "Painting";
Destroy(hit.rigidbody.gameObject.GetComponent<PaintingLife>());
addtoArray(hit.collider.gameObject);
Debug.Log(prefabs);
//hit.rigidbody.gameObject.transform.position = new Vector3(0, -100, 0);
hit.rigidbody.gameObject.SetActive(false);
hit.rigidbody.gameObject.GetComponent<PaintingLongLife>().enabled = (true);
//Destroy(hit.rigidbody.gameObject);
//Debug.Log(hit.collider.gameObject.name);
}
}
if (Input.GetMouseButtonDown(2))
{
instantiateList();
}
}
void addtoArray(GameObject obj)
{
prefabs.Add(obj);
}
void instantiateList()
{
for (int i = 0; i < prefabs.Count; i++)
{
prefabs[i].SetActive(true);
Instantiate(prefabs[i], spawnLocations[0].transform.position, Quaternion.Euler(-90, YAxisAngle, 0));
}
}
}
Comment
Best Answer
Answer by hameed-ullah-jan · Nov 27, 2018 at 05:29 AM
you can check if prefabs[i] is null, try prefabs.Remove (name); or prefabs.RemoveAt (_listCntr);
you can add this code in this function:` void instantiateList() {
for (int i = 0; i < prefabs.Count; i++) { if(prefabs[i] == null){ prefabs.RemoveAt(i); }
for (int i = 0; i < prefabs.Count; i++)
{
prefabs[i].SetActive(true);
Instantiate(prefabs[i], spawnLocations[0].transform.position, Quaternion.Euler(-90, YAxisAngle, 0));
}
}`
Thank you so much - this was the answer!!! Although I needed to put it inside of the void update function so that it would clear all the empty slots consistently, and not just one slot at a time on click.
Really appreciated the help - you folks are true angels