SetMaterial() causing System.AccessViolationException

I have StaticModel components for which I need to change the material frequently. However, it seems consistent that the third time I attempt to set the material, I get the exception. I've tried it two ways:

node.GetComponent<StaticModel>( 0 ).SetMaterial( material );

and

node.RemoveAllComponents();
var component = node.CreateComponent<StaticModel>( CreateMode.Local );
component.Model = CoreAssets.Models.Sphere;
component.SetMaterial( material );

Same exception both ways. I have only tested it in UWP project.

Best Answer

Answers

  • BenColemanBenColeman USMember ✭✭

    So, looking at this thread, I found a clue.

    When the material is being set, the reference to the old material is discarded, which means the old material may get destroyed completely. I manually added references to the prior material using material.AddRef() before setting the new material and the issue went away.

    This may be the key to other System.AccessViolationException exceptions I've been getting.

  • EsaKEsaK SEMember ✭✭

    What I found out the last time I had similar problems with the material is that if you create/clone a material in code you must use material.AddRef(), but if the material is loaded through the ResourceCache you shouldn't need it.

  • EgorBoEgorBo BYXamarin Team ✭✭✭

    The problem is that all native objects are allocated with Refs=0 by C#, so when you add a ref and then remove - it triggers 'delete'. I am trying to fix it now but still experiencing some issues.

Sign In or Register to comment.