- Home /
Extending a class
Lets say i had a simple class:
class Test extends UnityEngine.Object{
private var pos : Vector3;
function _get(){
pos = GameObject.Find("Main Camera").transform.position;
return pos;
}
}
function Start () {
var testClass : Test = new Test();
print(testClass); //prints Null
print(testClass._get());//prints correct value
}
The problem is that by extending the class - it always gets the value Null, but is actually not Null...
I dont know if "extends UnityEngine.Object" is correct, but it's the only way i could get "GameObject.Find" to actually work.
Any help would be appreciated.
On an unrelated note - how exactly are we supposed to post code snippets here?
There is a button to format code. Either that or add 1 tab or 4 spaces in front of the code.
Also what's exactly the reason you want to derive from UnityEngine.Object ins$$anonymous$$d of $$anonymous$$onoBehaviour
Answer by Tseng · May 01, 2012 at 02:20 PM
A look at the Unity3D Documentation could have solved your problem :)
.transform .rigidbody .collider
etc. are properties of the Component class (UnityEngine.Component). They do not exist in UnityEngine.Object.
If you want to attach your script to an object and access it's components (transform, rigidbody, colliders are all components) you must derive the script from component too.
http://unity3d.com/support/documentation/ScriptReference/Component
Usually all scripts which get attached to the GameObjects are derived from UnityEngine.MonoBehaviour. All default Unityscripts automatically derive from MonoBehaviour.
well if i use UnityEngine.$$anonymous$$onoBehaviour ins$$anonymous$$d of UnityEngine.Object the class is still Null, thanks for the code format advice though :p
Classes which derive from Component are not supposed to be initialized via constructor. They are automatically initialized from the Unity Engine when attached to an object.
But if you want to make class types (like you'd do in C#) you should actually derive from "System.Object".
class Test extends System.Object
would equal to C#
public class Test {
}