Use c# "ref" with a GameObject or Component
What i basically want to do:
void Method(ref SpriteRenderer sr)
{
sr.color = ...
....
}
....
Function(ref someGameObject.GetComponent<SpriteRenderer>());
So I want a Method to work on a specific type of component (or alternatively work on a gameobject and get that gameobjects components). But i can't just use the code above, it says the SpriteRenderer is not assignable.
Answer by Owen-Reynolds · Aug 15, 2017 at 03:59 PM
The error message is correct. ref
can only be used with a variable you can directly assign. Using sr=
in the function would be like ago.GetComponent<SpriteRenderer>()=
in the main program, which clearly isn't allowed (you have to use the Destroy command, and then AddComponent to make a new one.)
But you're probably just confusing real reference variables with C#\Java reference types. That's very common, and it's confusing the way C# double-uses the word reference (even the official microsoft pages get it wrong.) You probably just need the 2nd way, and not the first, which is the extra ref
keyword.
sr
is a pointer, so you're allowed to make real changes to your spriteRenderer through sr.color=
. It's hidden, but sr.color
is really: follow the pointer from sr to your spriteRenderer; now change the color.
Your answer
![](https://koobas.hobune.stream/wayback/20220612132751im_/https://answers.unity.com/themes/thub/images/avi.jpg)