- Home /
You are trying to create a MonoBehaviour using the 'new' keyword.
Hello this is my class
//Factory
public class ColorFactory
{
private static Dictionary<Colors, Func<ColorMatch>> colormap = new Dictionary<Colors, Func<ColorMatch>> ()
{
{Colors.BlueMaterial, () => {return new BlueMaterial(); }},
{Colors.OrangeMaterial, () => {return new OrangeMaterial(); }},
{Colors.PurpleMaterial, () => {return new PurpleMaterial(); }},
{Colors.RedMaterial, () => {return new RedMaterial(); }},
{Colors.YellowMaterial, () => {return new YellowMaterial(); }},
{Colors.GreenMaterial, () => {return new GreenMaterial(); }}
};
public static ColorMatch CreateColorFromName (string name)
{
Colors getType = (Colors)Enum.Parse (typeof(Colors), name);
return colormap[getType]();
}
}
How to fix this problem, I don't really understand.
I know that this is c# way to make a new thing, but how to do it in Unity ?
I found that something with g
gameObject.AddComponent<BlueMaterial>()
But this is not working.
I need help )
Answer by Pendrokar · Jul 25, 2014 at 09:29 AM
Classes that inherit MonoBehavior(class myClass : MonoBehavior) cannot be instantiated/created using the "new" keyword.
See if "Colors" or any of the "*Material" classes inherit MonoBehavior.
Answer by uanmanarmy · Jul 25, 2014 at 09:53 AM
The problem was not here :)). Was above in the code, also with this kind of c# style problem.
I fixed it like this
EnergyBarScript energyBar = GameObject.Find("Items").GetComponent<EnergyBarScript>();
Maybe Other ideeas?
That is a different question/problem from what you originally posted. Also badly worded, make a new question regarding this issue. Your original problem was regarding the use of the "new" keyword.
yes, the problem was with new keyword. but not in the script above. The log was shown there, but actually the problem was when I created an object of that class.
I created like this
EnergyBarScript energybar = new EnergybarScript();