- Home /
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.
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,
Yoerick
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/
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Compiler error - wrong target 1 Answer