- Home /
Question about Inheritance in Unity
I am using inheritance (C#) with a base class that has
public GameSystem temp = (GameSystem)GameObject.Find("Manager").GetComponent("GameSystem");
and I want my subclasses to be able to use temp, but whenever i try to use temp i get this error
NullReferenceException: Object reference not set to an instance of an object TargetControl.OnMouseDown () (at Assets/Scripts/TargetControl.cs:37) UnityEngine.SendMouseEvents:DoSendMouseEvents()ne.SendMouseEvents:DoSendMouseEvents()
But this works. But if I replace Debug.log with the base class object it errors.
GameSystem temp = (GameSystem)GameObject.Find("Manager").GetComponent("GameSystem");
Debug.Log(temp.gameTimer);
Answer by Jesse Anders · Feb 17, 2011 at 01:02 PM
You can use the generic version of GetComponent() instead, e.g.:
GameSystem temp = GameObject.Find("Manager").GetComponent<GameSystem>();
However, I don't think you can use Unity API functions such as Find() in field initializers or constructors (or at least you're not supposed to). Instead, you should perform initializations of that sort in Awake() or Start().
Not sure what you mean about the Debug.Log() part.
Intersting. It worked, thank you. So inheritance in Unity is not like normal inheritance in C#? Because the base class var is not quite available to base classes, but can be accessed if I go through Get Component. I figure since if the var is in the base class, I should be able to access it in the subclasses. But, I must use GetComponent as this is how Unity handles inheritance?
Why are functions in the base class available to the sub-classes, but not variables?
I'm not completely clear on your question, but there shouldn't be anything particularly unusual about how inheritance in C# works with respect to Unity. In other words, the behaviour should be the same as in any other C# application (AFAI$$anonymous$$, at least).
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Inheritance in C# and Unity3d 1 Answer
Grabbing an Inherited Variable 0 Answers
Destroying Elements From An Array 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer