组件上的对象属性设置之后怎么获取的是null呢?

是要做包裹功能.
包裹中, 每一个道具都是一个动态生成的node.
我给这个node设置了一个组建 叫 PropItem
PropItem里面有一个prop属性和id属性

在生成每一个道具的node的时候, 我把PropItem组件取出,
把遍历的道具给赋值上去.
node.getComponent(PropItem).id=prop.id;
node.getComponent(PropItem).prop=prop;
但是当我在点击该道具节点的事件里, 取出PropItem这个组件的时候, id是能获取到的. 但是prop获取不到, 是个null
求教, 这是因为什么原因呢?

应该是代码逻辑有问题,可以贴出代码。

这是遍历和设置的地方

map.forEach(prop => {
            let propNode = instantiate(this.propPrefab);
            propNode.name = "prop:" + prop.getUid() + ":" + prop.sid + ":" + prop.getCount();
            propNode.getChildByName("bg").getComponent(Sprite).color = Color.RED;
            // 设置图标
            propNode.getChildByName("icon").getComponent(Sprite).spriteFrame = ResourceManager.getPropIcon(prop);
            // 设置数量
            let count = prop.getCount();
            if (count > 1) {
                propNode.getChildByName("count").getComponent(Label).string = "" + count;
            }
            propNode.getComponent(PropItem).sid = prop.sid;
            propNode.getComponent(PropItem).prop = prop;
            propNode.parent = scrollView.content;
        })

用的时候 sid 是可以取到并且是正确的, 但是prop这个对象就是空的

在箭头函数里上面代码下方打印一下console.log(JSON.stringify(prop));

这里都是没问题的, 道具都是正确显示出来了的…而且也没有为null的元素

你只贴了赋值的地方,点击的呢?你描述的问题不在点击时取值上吗?

@ccclass('PropItem')

export class PropItem extends Component {
    // 道具uid
    uid: number;
    // 道具类型
    typs: number;
    // 道具sid
    sid: number;

    prop: Prop;

    start() {

    }

    public press() {
        console.log(".................... " + this.uuid + ", " + this.sid);
        EventManager.emit(Consts.PRESS_PROP_NODE, this.prop);
    }
}

点击的时候,直接调用的 press()方法. 这里的sid都是正常的, 但是prop就是null

是接收事件的地方拿到了null还是触发事件前就是null?

感谢一步一步的提示.
我多打印了一些数据, 发现我对提示理解错误了

Cannot read property ‘name’ of null’
我理解的是 不能读取 null对象的name属性
但实际情况是 这个对象的name是null

嗯,提一个建议,代码编写时,最好多用缓存,这样测试断点时栈信息一目了然,代码的可阅读性也会有所提高~

例如:
propNode.getChildByName("bg").getComponent(Sprite).color = Color.RED;
可以改为

let propBgNode = propNode.getChildByName("bg");
let propBgSprite = propBgNode.getComponent(Sprite);
propBgSprite.color = Color.RED;
1赞

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。