- Home /
Call a class in c#
Hello, i`m having a problem that i can`t understand, for example in js i have:
//In a script named MenuElement i have:
class MenuElements
{
//My public vars and enums methods etc
}
-------------------------------------------
// And then in another Script named MenuWindows
//code...
var myElements: MenuElements[];
And this works perfectly, the problem is when i try to do the same thing in c# it simply doen`t work and gives error "NullReferenceException: Object reference not set to an instance of an object"
// In script MenuElements
public class MenuElements
{
//My public vars enums methods etc
}
//In Script MenuWindow
public class MenuWindow : MonoBehaviour
{
public MenuElements[] myElements;
void OnEnable()
{
if (myElements.Length > 0)
for (var i = 0; i < myElements.Length; i++)
{
//myElements[i] = new MenuElements();
myElements[i].SetParent(this);
myElements[i].parentSize.x = size.x;
myElements[i].parentSize.y = size.y;
startPosition = position;
myElements[i].percentage = true;
myElements[i].Start();
}
}
}
I have tried allot of things but i can`t put it to work, what am i doing wrong? My objective is to instantiate the class MenuElements inside MenuWindow, after inserting the number of instances of that class in the inspector.
Answer by GuyTidhar · Feb 20, 2013 at 02:51 PM
Add: 'System.Serializable' attribute above your non monobehvaiour class
[System.Serializable]
public class MenuElements
{
//My public vars enums methods etc
}
Indeed... (+ Character so I can post this. But now that's a bundle more characters. What a predicament!)
Answer by Bunny83 · Feb 20, 2013 at 02:51 PM
In UnityScript every class you create gets by default the System.Serializable attribute. In C# you have to add it to your class so it's displayed in the inspector. When it's displayed in the inspector you don't need to create the array or the classes since that is done by the inspector.
[System.Serializable]
public class MenuElements
{
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Reflection on Unity class 1 Answer
C# NullRefException accessing static class, array value 1 Answer
Programmmed Animation (making transform move to vectors with code) 0 Answers