- Home /
Getting Null From List
I have 2 c# script, NPCManager and NPCs. NPCManager.cs using UnityEngine; using System.Collections;
public class NPCManager : MonoBehaviour {
public int npcID;
public int npcStage;
public string npcName;
public string npcDialog;
public NPCManager(int ID, int Stage, string Name, string Dialog)
{
npcID = ID;
npcStage = Stage;
npcName = Name;
npcDialog = Dialog;
}
}
the NPCs.cs using UnityEngine; using System.Collections; using System.Collections.Generic;
public class NPCs : MonoBehaviour {
public List<NPCManager> NPCList = new List<NPCManager>();
void Start () {
NPCList.Add( new NPCManager(1, 0, "test", "test" ) );
}
}
there is no error, no warning. in the inspector which NPCs added, when i start the game the list added 1 size but it say "None (NPCManager)".
i want it show the NPCManager variable.
Answer by Xtro · Jul 24, 2014 at 04:01 PM
First of all, generally, you shouldn't use class constructors on classes derived from monobehaviour. And I don't get why you need that constructor at all.
Secondly, when you initiate a class in the member definition line, it's the same thing as writing it into the constructor which is wrong for monobehaviour.
Remove the NPCManager constructor and try this for NPCs class:
public class NPCs : MonoBehaviour {
public List<NPCManager> NPCList;
void Start () {
NPCList = new List<NPCManager>();
NPCList.Add( new NPCManager(1, 0, "test", "test" ) );
}
}
The thing you did was good in the context of C# and .NET but not in Unity monobehaviour.
i know nothing about what you said. class derived, class constructors, behavour, member line ,etc.
can you post the NPC$$anonymous$$anager script so at least i know what constructor is.
i simply following this tutorial and convert from js to c# https://www.youtube.com/watch?v=rbW_gTwvTSA∈dex=2&list=PLLflfFtpkLT-ZunZu5nQ0pTspsT3GB9qS
Constructor is the creator function of a class and it has the same class name. So in your script this is the constructor :
public NPC$$anonymous$$anager(int ID, int Stage, string Name, string Dialog)
{
// ........
}
Remove this function from NPC$$anonymous$$anager class and use the code I gave you for NPCs class.
I advice you to study Object Oriented Program$$anonymous$$g on C#. Without it, you won't be improving your self on program$$anonymous$$g.