I have an extension method for resetting Texture2D:
public static class MyExtensions
{
public static void Reset(this Texture2D tex)
{
if(tex == null) tex = new Texture2D(256,1,TextureFormat.RGBA32,false);
for(int i=0;i<256;i++)
{
tex.SetPixel(i,1,Color.clear);
}
tex.Apply();
tex.wrapMode = TextureWrapMode.Clamp;
}
}
When i try to call it in another class:
if(ref_tex == null) ref_tex.Reset();
ref_tex.SetPixel(i,1,new Color(r,g,b,1f));
Unity Log always throws an error on the second line: UnassignedReferenceException: The variable ref_tex has not been assigned.
Do I do something wrong?
Your best bet is to use a plain old static method with a ref parameter.
public static class ResetTexture {
public static void Reset(ref Texture2D tex) {
if(tex == null) tex = new Texture2D(256,1,TextureFormat.RGBA32,false);
for(int i=0;i<256;i++) {
tex.SetPixel(i,1,Color.clear);
}
tex.Apply();
tex.wrapMode = TextureWrapMode.Clamp;
}
}
// Somewhere else
if (ref_tex == null) ResetTexture.Reset(ref ref_tex);
ref_tex.SetPixel(i,1,new Color(r,g,b,1f));
The reason you can’t use an extension method is due to how parameters are passed in C#. Parameters are by default passed by-value. Changing the parameter using =
inside the method has no effect on the variable passed to the method.
void Start() {
var a = "Hi";
Debug.Log(a);
Change(a);
Debug.Log(a);
}
void Change(string b) {
Debug.Log(b);
b = "Hello";
Debug.Log(b);
}
Produces output:
Hi
Hi
Hello
Hi
When you want changes inside a method to propagate back to the caller you use the ref keyword.
void Start() {
var a = "Hi";
Debug.Log(a);
Change(ref a);
Debug.Log(a);
}
void Change(ref string b) {
Debug.Log(b);
b = "Hello";
Debug.Log(b);
}
Produces output:
Hi
Hi
Hello
Hello
However, the first parameter of an extension method can’t be a ref
parameter.
void Change(this ref Texture2D b) {
// Compile Error: "The parameter modifiers 'this' and 'ref' cannot be used together."
}
This means you can’t use ref
to modify the object on which you call an extension method.