x


Why can't I set GetComponent(Some_Component).enabled = false; ?

Sorry for the newbie question. I have noticed that this gives me an error ('enabled' is not a member of 'UnityEngine.Component':

mainCamera.GetComponent(AudioListener).enabled = false;

But this seems to be work fine:

var myListener:AudioListener = mainCamera.GetComponent(AudioListener);

myListener.enabled = false;

Is there a way to access the component without using a variable?

more ▼

asked May 05 '10 at 10:18 PM

Zootie gravatar image

Zootie
76 5 6 11

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

2 answers: sort voted first

The way to do it without creating a variable is to cast the Component to an AudioListener:

(mainCamera.GetComponent(AudioListener) as AudioListener).enabled = false;
more ▼

answered May 05 '10 at 11:22 PM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

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

The compiler is right, "enabled" is not a member of Component. AudioListener inherits from Component, so it's got some extra things. But if you look at the docs for GetComponent, you'll notice that it returns a Component. What you're doing in your second example is implicitly casting the component that is returned as an AudioListener. The explicit way to do it would be

var myListener = mainCamera.GetComponent(AudioListener) as AudioListener;

Ad any rate, you can safely expect that when you call GetComponent with the type AudioListener, it can be cast as an AudioListener. If you don't want to explicitly declare a temporary variable, the following should work:

(mainCamera.GetComponent(AudioListener) as AudioListener).enabled = false;

My personal preference is to leave the temporary variable, as it's more human-readable, and a little bit clearer what you're doing without all those parentheses, but that's just me (and probably a number of other people, as well).

more ▼

answered May 05 '10 at 10:39 PM

burnumd gravatar image

burnumd
3.3k 22 34 71

That's C# syntax, which won't work in Javascript.

May 05 '10 at 11:24 PM Eric5h5

Whoops, you're correct. C# on the brain.

May 06 '10 at 12:43 PM burnumd
(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:

x1029
x405

asked: May 05 '10 at 10:18 PM

Seen: 2931 times

Last Updated: May 06 '10 at 08:14 AM