- Home /
The question is answered, right answer was accepted
Trying to learn Generics
I've stored data in the inspectors of various Prefab objects (e.g., LevelData, EnemyData, etc.)
As these all need to be instantiated and then kept around for referencing, I'm trying to group them all under a persistent DataManager object that will instantiate them all on awake.
For this, I'm trying to create a class that can store the different data scripts generically, but I haven't really touched generics before. I've written the below to demonstrate, but I know it's wrong… can anyone help?
using UnityEngine;
using System.Collections;
public class DataManager : MonoBehaviour {
public class DataObjects where T : Component
{
public Object dataPrefab;
private T instance;
}
public DataObjects[] dataObjects;
static DataManager instance;
void Start ()
{
DataManager dm = FindObjectOfType( typeof(DataManager) );
if ( dm != null && dm != this )
Destroy( gameObject );
instance = this;
DontDestroyOnLoad( gameObject );
InstantiateData();
}
private void InstantiateData ()
{
for ( int i=0; i < dataObjects.Length; i++ )
{
GameObject tmpObj = Instantiate( dataObjects[i].dataPrefab );
tmpObj.transform.parent = transform;
dataObjects[i].instance = tmpObj.GetComponent< T >();
}
}
}
Answer by fafase · Dec 14, 2014 at 07:25 PM
Your question is not really suitable here since it is basically a question on how to use generic and you will get long and detailed answers online, particularly from msdn.
Your error is there:
public class DataObjects<T> where T : Component
{
public Object dataPrefab;
private T instance;
}
you are missing the diamond indicating the generic. And you use:
DataObjects <ScriptName> object = new DataObjects<ScriptName>();
Now your instance is of type ScriptName but does not have any object it will point to and no way to assign any since it is private. You should have a property or method to set it:
public class DataObjects<T> where T : Component
{
public Object dataPrefab;
private T instance;
public DataObject<T>(){}
public DataObject<T>(T reference)
{
instance = reference
}
public DataObjects<T>Instance{get{return instance;}}
}
void Start()
{
DataObjects<ScriptName>data = new DataObjects<ScriptName>(gameObject.AddComponent<ScriptName>());
}
In this case, the instance will point to a component attached to the game object since they have to.
Thanks. I tried reading the $$anonymous$$SDN docs but was still struggling to understand. Your code has helped!
Follow this Question
Related Questions
Reading and Storing External Data into Memory (From Text) 1 Answer
Database-like arrays 1 Answer
How to save and load any data type? 1 Answer
Lists and Structs instead of Arrays? 4 Answers