- Home /
C#: Declaring a script as a variable
public class WallProperties : MonoBehaviour
{
public Door door;
public bool IsDoor(bool enable) //enable=true
{
if(enable)
{
print (enable); //prints true
door=new Door();
door.DoorStart(); //sets values to default
print(door.GetStyle ()); //prints current value
print ((door==null)?"True":"False"); //prints true
}
return(door==null); //returns true
}
...
}
- I am trying to have the 'door' variable not NULL
- The mono class is not attached to anything
- It gave me lip when the "new Door()" was removed
- With the "new Door()" I am able to access the Door class
However, the variable 'door' stays NULL. Is there a way that the 'door' variable can be declared and not be NULL or should I just have a boolean class variable for the door?
If door is derived from $$anonymous$$onobehavior, then it will need to be attached to a game object...either one you create dynamically or one you create in the editor. Then you will use GetComponent() on the game object with the script to initialize 'door', or you can use drag and drop in the inspector.
I,m curious.... how is door equals NULL and is not crashing here?
door.DoorStart(); //sets values to default
print(door.GetStyle ()); //prints current value
Answer by salex100m · Nov 23, 2013 at 01:33 AM
you need to properly instantiate your Door if it is an object. Or you can add the class as a component and then create a reference to that component.
Answer by jovino · Nov 23, 2013 at 02:34 AM
When you are not attaching your class to a gameobject you need to use ScriptableObject.
http://docs.unity3d.com/Documentation/ScriptReference/ScriptableObject.html
A class you can derive from if you want to create objects that don't need to be attached to game objects.
This is most useful for assets which are only meant to store data.