- Home /
Why are my MonoBehaviour methods not called?
I have the following very simple code; the script is attached to my game character:
class NeuralNetController extends MonoBehaviour {
function Start()
{
Debug.Log("Start called");
}
virtual function Update()
{
Debug.Log("Update called");
}
}
but it does not work - that is, neither method gets called. When I remove the class syntax, like this:
function Start() { Debug.Log("Start called"); }
virtual function Update() { Debug.Log("Update called"); }
then it works fine. Do I have the syntax wrong? Or should I extend from another class? Or is there something else going on?
Just as an experiment, I also added the virtual keywords to the function declaration of the first example; that too, did not work.
(If you are wondering why I don't simply use the second method - since it works - it is because I actually need to extend from another class that extends from MonoBehaviour. I just took out the irrelevant detail.)
Do you have any other code in the script file? Any variables, functions, or other classes? That "irrelevant detail" might actually be causing things to break down. :)
The answer below was it (of course, I also made sure that the problem occurred with the irrelevant stuff removed ;-)
Why did you make your Update function virtual? It doesn't need to be for Unity to call it.
Answer by Brian-Kehrer · Nov 21, 2009 at 01:36 AM
Most likely the script is not named exactly 'NeuralNetController', which it must be if you extend the monobehaviour. The class name and script file name must match, if you use C#, it will tell you this. I dropped your script into unity and renamed it appropriately, and it worked perfectly.
The javascript compiler is unfortunately very prone to letting you make unintended mistakes. For this reason alone, I highly recommend using C#. It's syntax is more strict, and for that reason, you will end up making fewer mistakes from simple typos, as the compiler will gently warn you, instead of silently doing something unintended.
using UnityEngine; using System.Collections;
public class NeuralNetController : MonoBehaviour{
void Start(){ Debug.Log("Start called");
}
public virtual void Update(){ Debug.Log("Update called"); }
}
Thanks $$anonymous$$, that was it. Can't believe it was that simple!
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
One of my scripts has no check-box next to it in Inspector 2 Answers
How to import the object from server to unity 2 Answers
How to use intelisence in mono (in order to get all the contents of other script file) 1 Answer
monobehaviour script accessing problem causes error 1 Answer