- Home /
getting GameObject from Array and then instantiating
For my quest system, I store empty's with a script for that quest (questBlock) and instantiate them when beginning the quest. This code actually runs fine, but I want to organize the questBlocks into an arraylist (ql) for easier sorting (the code that has been commented out).
Problem is, I get a conversion error on "Quest = ql" and another on "Instantiate(ql[10]"
if questBlock is a GameObject when added to an arraylist, why is it not a GameObject when accessed?
using UnityEngine;
using System.Collections;
using System;
public class QuestSystem : MonoBehaviour
{
public GameObject questBlock;
public ArrayList ql = new ArrayList();
void Start ()
{
ql.Add(questBlock);
//GameObject quest = ql[0];
//GameObject current = (GameObject) Instantiate(ql[0], transform.position, transform.rotation);
GameObject current = (GameObject)Instantiate(questBlock, transform.position, transform.rotation);
}
}
Answer by OrkhanAlikhanov · Jul 06, 2016 at 02:24 PM
ArrayList contains an array of System.Object. Use List<GameObject>
instead.
public var ql = new List<GameObject>();
Or Cast the System.Object into GameObject:
GameObject quest = ql[0] as GameObject ;
GameObject current = (GameObject) Instantiate(ql[0] as GameObject, transform.position, transform.rotation);
I'd strongly recommend using List<GameObject>
Answer by HarshadK · Jul 06, 2016 at 07:32 AM
ArrayList stores its items as Object. You can check the source code for ArrayList here. So after getting the item you need to cast it to your item type i.e. GameObject in this case.
Your answer
Follow this Question
Related Questions
Referencing instantiated objects at runtime 2 Answers
Cannot instantiate gameobject 3 Answers
Reference by Instance ID? 2 Answers