NullReferenceException when changing a shader property during OnEnable of a parent component

Avatar
  • updated
  • Fixed

Hi Freya,

I may found a little bug.

Let's assume the following structure in the hierarchy:

  • ParentGameObject
    • ChildObject with Shapes (Disc)

Whenever the ParentGameObject get's enabled, I use OnEnable to access the child Disc-Shape and set AngRadiansEnd


However, this leads to a NullReferenceException:

NullReferenceException: Object reference not set to an instance of an object
Shapes.ShapeRenderer.ApplyProperties () (at Assets/Shapes/Scripts/Runtime/Components/ShapeRenderer.cs:254)
Shapes.ShapeRenderer.SetFloatNow (System.Int32 prop, System.Single value) (at Assets/Shapes/Scripts/Runtime/Components/ShapeRenderer.cs:273)
Shapes.Disc.set_AngRadiansEnd (System.Single value) (at Assets/Shapes/Scripts/Runtime/Components/Disc.cs:110)

I tracked it down to the following line:

rnd.SetPropertyBlock( Mpb );

rnd is null. 

The "problem" is that rnd is set during OnEnable in the ShapeRenderer. However, the OnEnable of the parent is invoked before the OnEnable in the child object, that's why it's null in that case.

I can work around that, however I think it can be solved in Shapes and maybe do a null check before trying to access rnd.

Please let me know, if you need further information or a sample project for reproduction.

Reporting a bug? please specify Unity version:
2020.1.3f1
Reporting a bug? please specify Shapes version:
2.2.0
Reporting a bug? please specify Render Pipeline:
Avatar
Freya Holmér creator
  • Fixed

should be fixed now in the version after 2.2.0!

Avatar
Manuel Rauber

Hi Freya,

thanks for your fast answer. I hope it's ok to add another NullRef here that is kind of similar.

I've a script that gathers some ShapeRenderer and set their color. To reflect the color change in the editor, I use OnValidate:

    [SerializeField]
    private Color Color;

#if UNITY_EDITOR
private void OnValidate()
{
UpdateColor();
}
#endif

private void UpdateColor()
{
Shapes?.ForEach(shape => shape.Color = Color);
}

That leads to another NullReference exception, because my OnValidate is run before the Shapes OnValidate.

Avatar
Freya Holmér creator
  • Planned

null checking unity objects is generally not very cheap, so unfortunately sometimes we get these edge cases! it's especially important in ApplyProperties since it's potentially called every frame

anyhow! I should be able to cover up this edge case, thanks for the report :)