Using scripts change spriteState problem for 9-slice

I try use scripts to change the highlight sprite of a toggle created by dropdown.

For now, I have successfully change the highlight sprite, but I found the 9-slices for sprite not working.

var firstItem = gameObject.transform.Find("Dropdown List/Viewport/Content/Item xxxxxxxxx");
SpriteState newFirstState = firstToggle.spriteState;
var sprite = Resources.Load<Sprite>("xxxxxxx");
newFirstState.highlightedSprite = sprite;
firstToggle.spriteState = newFirstState;

the outcome is the above one

but what I expected is below one

I try to change the item background, found 9-slice working.

Anyone can help to see this problem?

Looks like a bug! After the code runs, press pause (or execute Debug.Break() to instantly pause) and find what’s in that sprite field. Click it. Is it the one you expected? Is the Image still set to sliced? etc. etc. etc.

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.

Actually what I want to know is when I change the SpriteState, the 9-slice not applied, this may affected by engine action. I try to change button sprite and toggle, seems have same action.

Did you set the Image to use Sliced AFTER you set the Sprite?

It’s entirely possible it would reset if there was no sprite, or be wrong for some other reason.

If you know you need a feature, write some code to turn it on.