x


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);
more ▼

asked Feb 17 '11 at 11:39 AM

RoR gravatar image

RoR
316 73 86 97

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Feb 17 '11 at 01:02 PM

Jesse Anders gravatar image

Jesse Anders
7.3k 7 17 48

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?

Feb 17 '11 at 05:19 PM RoR

Why are functions in the base class available to the sub-classes, but not variables?

Feb 17 '11 at 05:19 PM RoR

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 (AFAIK, at least).

Feb 17 '11 at 08:31 PM Jesse Anders
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x394
x155
x134

asked: Feb 17 '11 at 11:39 AM

Seen: 1717 times

Last Updated: Feb 17 '11 at 11:39 AM