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.
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.
Answer by karl_
Nov 06, 2011 at 02:52 AM
This did the trick for me:
scriptName = (scriptName)target;
go = (GameObject)scriptName.gameObject;
Answer by Yoerick
Nov 03, 2011 at 08:41 PM
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,
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/
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a user guide.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
Answers and Comments
4 People are following this question.
Multiple Cars not working
Distribute terrain in zones
i need help removing an error in my targetting/attack script
Override Transform Inspector for specific GameObjects
Adding tags to static int.