Object list is null?
I need to instantiate an object from a list, if it isn't undefined, but the code don't make it. Pseudo-code:
list<GameObject> list = new List<GameObject>();
int number;
void Update(){
if(list[number] != null){
Instantiate(list[number...);
}
}
If you are going to instantiate object from the list, first, the list needs to contain something. Your psuedo code doesn't show the list as public, so it wouldn't be populated in the inspector. (Unless your actual code is public for this)
Also, doing this in update, will instantiate an object every frame, probably not what you are wanting here.
You will also want to make sure that number is not outside of the bounds of the array.
Hi, the list have a method to get objects, and a condition to instantiate, the problem is what you said, the value is outside bounds of list, there is a way to don't instantiate the object if it is outside bounds? (Sorry for my English) The current code:
using UnityEngine;
using System.Collections.Generic;
public class inventory : $$anonymous$$onoBehaviour
{
public List<GameObject> items = new List<GameObject>();
public int slots;
[HideInInspector] public int number; // O número pressionado - hotbar
private $$anonymous$$eyCode[] keyCodes = { // Array dos números possíveis - hotbar
$$anonymous$$eyCode.Alpha1, $$anonymous$$eyCode.Alpha2, $$anonymous$$eyCode.Alpha3,
$$anonymous$$eyCode.Alpha4, $$anonymous$$eyCode.Alpha5, $$anonymous$$eyCode.Alpha6, // Definem as "keys" para serem pressionadas
$$anonymous$$eyCode.Alpha7, $$anonymous$$eyCode.Alpha8, $$anonymous$$eyCode.Alpha9,
};
void Update()
{
// --- Hotbar
for (int i = 0; i < keyCodes.Length; i++) // Para cada $$anonymous$$eyCode processa um valor 'i'
{
if (Input.Get$$anonymous$$eyDown(keyCodes[i])) // Detecta o valor pressionado (poderia somar um a ele (para compensar o início em 0 das arrays) contudo, seria...
// ...removido no instantiate)
{
number = i;
if (items[number] != null)
{
Instantiate(items[number], new Vector2(transform.position.x, transform.position.y - 0.5f), Quaternion.identity, this.transform);
}
}
}
// ---
}
}
The comments are in portuguese.
Answer by Larry-Dietz · Dec 13, 2019 at 03:25 PM
Make the following change, to ensure that number is within the bounds of the array before trying to instantiate...
if (number < items.Count && items[number] != null)
{
Instantiate(items[number], new Vector2(transform.position.x, transform.position.y - 0.5f), Quaternion.identity, this.transform);
}
Hope this helps, -Larry
Your answer
Follow this Question
Related Questions
Prevent spawning if the gameobject has same position as a list of Vector3s using another list? 1 Answer
Check if a large number of gameobjects are colliding 1 Answer
Unknown Argument Out of Range Index Error On Card Game 1 Answer
Add Clones of GameObject to List(array) 0 Answers
Having trouble with instantiating bullets at multiple points via a list of transforms. 1 Answer