Null Reference Exception when using Buttons in C# (CE5.4)

#1
Hey, I recently tried to use the C# UI System 5.4 provides.

After trying out several different usages of the UIElement Button, I think this could be an engine bug.
When Instantiating a button and using the function RectTransform.Size the OnUpdate of the Image.cs file in Core.UI is throwing a Null Reference Exception.

One of the tested code snippets

Code: Select all

var button = SceneObject.Instantiate<Button>(this); button.RectTransform.Size = new Point(RectTransform.Width, 40f); button.RectTransform.Alignment = Alignment.Top; button.RectTransform.Pivot = new Point(0.5f, 1f); button.Ctrl.Text.Content = label;
Error (line 93 in Image.cs of Core.UI)

Code: Select all

_texture.ClampRect = ((Owner as UIElement).RectTransform).ClampRect;
Managing Director & Founder at WastedStudios

Visit us on our website, facebook or twitter.

Re: Null Reference Exception when using Buttons in C# (CE5.4)

#2
My guess is that the value of _texture is null. This could be caused by the BackgroundImageUrl or BackgroundImageInvertedUrl properties on the Button having the wrong values. So to fix it you can assign a the right image to the button.

You can also modify the file directly in the Core.csproj by changing the OnUpdate() of the Image class to the following:

Code: Select all

public override void OnUpdate() { if (_source != null && _texture != null) { if (!IgnoreClamping) { var rect = Owner.GetComponent<RectTransform>(); if(rect != null) { _texture.ClampRect = rect.ClampRect; } } else { _texture.ClampRect = new Rect(); } if (Color.A > 0.05f) { var rect = Owner.GetComponent<RectTransform>(); if(rect != null) { _texture.Angle = rect.Angle; } _texture.Color = _color; _texture.TargetCanvas = ParentCanvas; var r = GetAlignedRect(); _texture.Draw(r.x, r.y, r.w, r.h, SliceType); } } }
This adds some more null-checks and doesn't assume that the owner is always an UIElement.

Re: Null Reference Exception when using Buttons in C# (CE5.4)

#3
Thank you very much for the fast answer!
Apparently the mistake was on my side as I assumed, that the default files stores in "libs/ui" can be deleted in the blank project.
After getting it back in there, it is working. If anyone else got this problem -> move the default UI textures back into the "Assets/libs/ui" folder.

For future releases it may make sense to move hardcoded required textures into the engine itself.

Thanks again!
Managing Director & Founder at WastedStudios

Visit us on our website, facebook or twitter.

Who is online

Users browsing this forum: No registered users and 3 guests

cron