cocos creator 如何用代码更换button的图片

let button = cc.find(“button”,this.node).getComponent(cc.Button);
button.normalSprite.spriteFrame = new cc.SpriteFrame(cc.url.raw(“Images/game/btn_again_paihang_nor.png”));

我尝试用上面的代码给一个button更换图片 但是不好使,请教一下我该怎么做

我是去掉Button组件,然后直接给Sprite换spriteFrame。

图片要放在resources文件夹下才能加载到

我也不会 我来顶一下 别沉了

不在resources下面也能加载的到 Sprite用同样的方法就能换掉的

按你说的试了试,还真能显示成功,虽然报错—Sorry can not load ‘Texture/HelloWorld.png’ because it is not placed in the ‘resources’ folder.
另外,你的按钮所在节点上有没有sprite组件

从文档上来看 按钮里面有四个精灵 分别对应按钮的四种状态,而且我在Chrome中打断点 可以看到normalSprite 这个属性

按钮是个UI控件,需要配合渲染组件Sprite组件达到显示效果

另外这个cc.url.raw()下的路径到底需不需要包含在resources下还得问问其他人@jare,大神来瞄一眼

自顶别沉

图片是cc.Sprite组件的,所以修改cc.Sprite组件的spriteFrame就可以了。

记住这一点,就可以了,跟button实际上是无关的,当前,如果你的button设置了四个状态的spriteFrame,记得同时改变他们,。。。

只要是 cc.Sprite,修改它的spriteFrame,准会变,当然前提是你的spriteFrame需要已经加载了,要么通过属性拖动的方式,要么通过加载资源的方式。

var buildButton = this.node.getComponent(cc.Button); buildButton.normalSprite = new cc.SpriteFrame(cc.url.raw("resources/ui/main/building/" + buildInfo.icon + "_n.png")); buildButton.pressedSprite = new cc.SpriteFrame(cc.url.raw("resources/ui/main/building/" + buildInfo.icon + "_p.png")); this.node.on(cc.Node.EventType.TOUCH_END, this.parent.clickBuilding);

normalSprite就是SpriteFrame类型
图片需要放在resources文件夹下面,路径从resources开始

button有个interactable选项。
设置为true显示normalSprite。
设置为false显示disabledSprite。

不知道这个功能能否解决你的问题。

我通过node.GetComponent在button上面获取不到Sprite组件,直接给他赋值Sprite了。可以了。