- Home /
Texture2D Extension: Texture Still Null After Calling It
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?
i not sure but maybe problem that SetPixel in Reset method work more than 1 frame and you then call SetPixel again until first finish.
Answer by steakpinball · Jun 29, 2015 at 02:29 PM
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.
Thanks brianturner! You saved my day! But im quite confused why it doesn't work for Texture2D. I have a similar extension for AnimationCurve, which works perfectly. Also another for List works.
I feel extension method uses pass-by-ref, cause it modifies the data that passes inside the method. You have any idea on that?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Is it possible to RPC a C# extension method? 1 Answer
Flip over an object (smooth transition) 3 Answers