- Home /
Class transform "null" keyword error.
If my class is attachet to an object and extends Monobehaviour and set a transform from another script from another object I always get the "You are trying to create a MonoBehaviour using the new keyword.This is not allowed" warning....any clues on how to solve this ? the scripts actually work but I want to know what the warning means and what side effects it has.
the class script
pragma strict
class aClass extends MonoBehaviour {
var pos : Transform;
function aClass(a : Transform)
{
pos = a;
}
function Updater()
{
if(pos != null)
{
Debug.DrawRay(pos.position,Vector3(0,10,0), Color.red);
print("abba");
}
}
}
and the second script
pragma strict
var grid : aClass;
function Start () {
grid = aClass(gameObject.transform);
} function Update() { grid.Updater(); }
the warning appears because the transform in the second script and points at the constructor in the class script.
Answer by Xtro · Aug 12, 2013 at 01:37 PM
In unity, don't use class constructors unless you are developing an editor extensions. Always put your initialization code into Start event. If you need parameters for initialization, then write an init method with the parameter and call that method after you create the object. It should be something like that (C#)...
var object = (GameObject)Instantiate(<The prefab object you want to create>);
grid = object.GetComponent<aClass>();
if (grid) grid.Init(gameObject.transform);
--- BUT ---
If you want to create and use your own class just like a regular class (you won't attach it to any gameobject in the inspector or in the code) ... you shouldn't extend it from MonoBehaviour.
In that case, just remove the "extend MonoBehaviour" part from your code and it's ready to go.
Yes but if I delete the constructor with the class extending $$anonymous$$onobehaviour and assign the transform this way grid.pos = gameObject.transform I recieve a NullReferenceException a the transform assignment.
Try to debug to find which variable is null. $$anonymous$$y guess is grid is null.
did you try my code sample ?
Can you please write another sample in JavaScript? I get stuck in c# at the moment......still learning
Your answer
Follow this Question
Related Questions
How do i edit a constructor array in the inspector? 1 Answer
Can i set class vars automatically when calling class constructor with attributes? 0 Answers
new Monobehaviour as variable returns warning... 1 Answer
How can I instantiate a object with a constructor? 3 Answers
Finding class where current GameObject is assigned to as a var 1 Answer