- Home /
How do I run Start() inside a nested class?
I'm nesting classes to organise my code. However void Start() only works in the uppermost class, only "Hello 1" is logged:
using UnityEngine;
public class Data_Access : MonoBehaviour
{
void Start()
{
Debug.Log("Hello 1");
}
public class Fronts
{
void Start()
{
Debug.Log("Hello 2");
}
}
}
Is this possible or even reccomended? How else would achieve this?
Start
is one of the functions Unity will call, not you.
What are you actually trying to accomplish here?
Just access the instance of the subclass in your $$anonymous$$onoBehaviour's Start method, and call the subclass' Start method from there.
If your nested class is not a $$anonymous$$onoBehaviour (and it should not be), then to initialize the class use a constructor, or call an initialization function explicitly. For example:
public class Data_access : $$anonymous$$onoBehaviour {
private void Start () {
Fronts f = new Fronts(); // either let constructor initialize, or...
f.Init(); // ...explicitly call a public initialization function (you can name it whatever you want), but make sure it is only called once
}
public class Fronts {
public Fronts () {
// do here all the initialization you need, that you would usually do in Start()
}
public void Init () {
// or do it in an explicit init function
}
}
Note, that a constructor is more like Awake()
(because they are both called when the object is instantiated), and Start()
is more like an initialization function (because they are called before the object is updated for the first time).
Answer by Staarter · May 01, 2018 at 02:22 PM
The method Start() will only work into a class that inherits from MonoBehaviour.
You can do something like :
public class Data_Access : MonoBehaviour
{
private Fronts fronts = new Fronts();
private void Start()
{
fronts.Start();
}
}
public class Fronts
{
public void Start()
{
Debug.Log("Hello from Fronts class");
}
}
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Class and Array 1 Answer