- Home /
Accessing properties from variable
private var rend;
function Awake()
{
if (gameObject.GetComponent(TextMesh) != null)
rend = gameObject.GetComponent.<TextMesh>();
else if (gameObject.GetComponent(SpriteRenderer) != null)
rend = gameObject.GetComponent.<SpriteRenderer>();
}
Now if I want to use rend
rend.color.a = 0.5; // Gives an error: 'color' is not member of 'Object'
So I have to do it in this way:
(rend cast SpriteRenderer).color.a = 0.5; // if using SpriteRenderer
However, I have to do this maybe 100 times in my script and I have to always check which type I'm using making all this pointless. The idea behind this is to use the same variable to change things regardless what type is placed to gameobject. So I could always use like rend.color.a, because both TextMesh and SpriteRenderer have color properties.
Best way forward I can see is to create a wrapper class using reflection. might come back later with an example.
See @SirCrazyNugget's comment to his answer below. $$anonymous$$ore efficient then $$anonymous$$e would be.
Answer by SirCrazyNugget · Jul 29, 2014 at 10:43 PM
I'm not sure whether this has been bumped or UA's had a timelapse, either way you'd be better off just storing the reference to Color rather than the GO
private var color : Color;
function Awake(){
if(gameObject.GetComponent(TextMesh) != null){
color = gameObject.GetComponent.<TextMesh>().color;
}else if(gameObject.GetComponent(SpriteRenderer) != null){
color = gameObject.GetComponent.<SpriteRenderer>().color;
}
color.a = 0.5;
}
Obviously keep the reference to rend too if needed.
It still doesn't work. I get compiler error: 'a' is not a member of 'object'.
sorry, missed off the important part.
private var color : Color;
I guess you can't store object properties to a variable, then change them and see the change in original properties.
Now it stores color into the variable that you can only read, not change.
@SirCrazyNugget: this doesn't work as Color is a value type and not a reference type. When you assign a value type to a variable you copy the value and not a reference.
Ahh Cr*p forgot about Color being a value type.
Plan B: How about just creating a simple function which handles the types for you
function SetAlpha(rend, a : float){
if(typeof(rend) == Text$$anonymous$$esh) (rend cast Text$$anonymous$$esh).color.a = a;
if(typeof(rend) == SpriteRenderer) (rend cast SpriteRenderer).color.a = a;
}
function Start(){
SetColor(rend, 0.5);
}
And just create the necessary functions that way?