I made this script to spawn an object inside my UI when I pickup a gameObject.
public GameObject notePrefab;
public Transform contentPanel;
public List<Note> noteList = new List<Note>();
public void AddNotes (Note noteObject)
{
noteList.Add (noteObject);
foreach (var note in noteList)
{
GameObject newNote = Instantiate(notePrefab) as GameObject;
newNote.transform.SetParent(contentPanel);
}
}
Collecting one object is fine (of course :)) but if I collect a second object, it is added twice in my list.
using UnityEngine;
using System.Collections;
public class AddNotes : MonoBehaviour
{
public int noteIndex;
void Awake ()
{
}
void OnTriggerEnter (Collider other)
{
DialogueManager.instance.note(noteIndex);
Destroy(gameObject);
}
public void DoInteraction ()
{
DialogueManager.instance.note(noteIndex);
Destroy(gameObject);
}
}
Then to the dialogueManager script :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DialogueManager : MonoBehaviour
{
public static DialogueManager instance = null;
public Note noteText;
void Awake ()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public void dialogue (string messageCustom)
{
UIManager.instance.DisplayDialogue (messageCustom);
}
public void note (int index)
{
if (noteText != null)
UIManager.instance.AddNotes (noteText);
}
}
So I pickup, then info is sent to the DialogueManager and finally to the UImanager where I populate my list.
I don’t use index at the moment.
It almost looks like a poolmamanger. Every time you call AddNotes you add a new item + in loop every item in the list and spawn it, that means your not adding new items but spawn every thing in the list every time you call AddNotes + the new one.
They way i do it, is to have a collection of every item you instantiated.
Like this:
public List<GameObject> UIObjPool = new List<GameObject>();
then this to check if item is in the list:
public void PoolManager(GameObject GO)
{
foreach(Transform AGO in UIObjPool .transform)
{
if (GO.name != AGO.name)
{
GameObject newNote = Instantiate(notePrefab) as GameObject;
newNote.name = newNote.name+"ID"+newNote.GetInstanceID();
UIObjPool.Add(newNote);
break;
}
}
}