Question by
commodore · Jan 10, 2016 at 09:00 PM ·
c#copyconstructor
Copy constructor not copying referenced class
I've got a script that holds a Level class that looks like this:
public class Level : MonoBehaviour {
public Level (Level p_level) {
Debug.Log("p_level from constructor: " + p_level);
Id = p_level.Id;
Title = p_level.Title;
Icon = p_level.Icon;
}
public int Id { get; set; }
public string Title { get; set; }
public Texture2D Icon { get; set; }
}
In another script I'm trying to copy the level to a variable
Debug.Log("level: "+level);
Level copiedLevel = new Level(level);
Debug.Log("copiedLevel: "+copiedLevel);
But Debug.Log("copiedLevel: "+level);
returns "copiedLevel: null". So it's not copying the level for some reason.
Comment
Answer by corn · Jan 10, 2016 at 09:17 PM
You cannot instantiate a MonoBehaviour with new
. You must either make Level not inherit MonoBehaviour, or instantiate a prefab with a Level MonoBehaviour, or use AddComponent.
Your answer
Follow this Question
Related Questions
How to set SyncVarAttribute.hook? 1 Answer
Copying a list of lists of int's in c# 1 Answer
Copy Rotation in script C# 1 Answer
Passing in objects to class constructor 0 Answers
Copying a List of Lists in c# 0 Answers