x


Custom Editor - Cast target as GameObject?

I'm trying to access the MeshRenderer component from a Custom Editor, but I can't seem to figure out the syntax in C#.

In JS what I'm trying to accomplish:

 var mat : Material = target.renderer.material;

In C#, this is what I've got:

 GameObject go = (GameObject)target;
 Material mat = go.renderer.material;

However, Unity tells me that I can't cast target as a GameObject.

more ▼

asked Nov 03, 2011 at 03:36 PM

karl_ gravatar image

karl_
3k 115 111 138

The issue is that "target" is not the game object itself, it's the component attached to the game object that your custom editor edits. Which is why casting to (scriptName) works.

Jan 10, 2012 at 09:27 PM yoyo
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

This did the trick for me:

 scriptName = (scriptName)target;    
 go = (GameObject)scriptName.gameObject;
more ▼

answered Nov 06, 2011 at 02:52 AM

karl_ gravatar image

karl_
3k 115 111 138

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

Have you tried using the 'as' keyword instead? Like changing "(GameObject)target" to "target as GameObject"?

Another thing you can try is casting it to a transform first:

 Transform go = target as Transform;
 Material mat = go.gameObject.renderer.material;

hope it helps,

Yoerick

more ▼

answered Nov 03, 2011 at 08:41 PM

Yoerick gravatar image

Yoerick
864 5 10 22

While this didn't solve my issue, I did learn about the differences between prefix casting and fast casting: http://gen5.info/q/2008/06/13/prefix-casting-versus-as-casting-in-c/

Nov 03, 2011 at 09:23 PM karl_
(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:

x10253
x352
x82

asked: Nov 03, 2011 at 03:36 PM

Seen: 4269 times

Last Updated: Jan 10, 2012 at 09:27 PM